测试期间如何用Capybara+Selenium+Geckodriver动态开关代理
在Capybara+Selenium+Geckodriver中动态切换代理(无需重启Firefox)
嘿,我懂你想要的效果——不用关闭重启Firefox,在同一个测试会话里就能随时开启、关闭代理,灵活切换不同网站的访问方式对吧?你之前的代码已经能启动带代理的Firefox实例,但动态调整确实需要更巧妙的方法,我来给你分享个靠谱的方案:
核心思路:直接修改Firefox的偏好设置
Firefox的代理配置其实存在内部偏好设置里,我们可以通过Selenium执行JavaScript直接修改这些配置,不用重启浏览器就能生效。这个方法比旧的Stack Overflow方案更稳定,适配新版本的Firefox和Geckodriver。
具体实现代码
1. 开启代理(以你的127.0.0.1:9999为例)
@session.driver.browser.execute_script <<-JS // 设置为手动代理模式 Services.prefs.setIntPref("network.proxy.type", 1); // 配置HTTP代理地址和端口 Services.prefs.setCharPref("network.proxy.http", "127.0.0.1"); Services.prefs.setIntPref("network.proxy.http_port", 9999); // 配置HTTPS代理(和HTTP共用的话可以开启共享设置) Services.prefs.setCharPref("network.proxy.ssl", "127.0.0.1"); Services.prefs.setIntPref("network.proxy.ssl_port", 9999); Services.prefs.setBoolPref("network.proxy.share_proxy_settings", true); // 清空不需要代理的域名列表 Services.prefs.clearUserPref("network.proxy.no_proxies_on"); JS
2. 关闭代理(恢复系统默认设置)
@session.driver.browser.execute_script <<-JS // 设置为使用系统默认代理(相当于关闭手动配置的代理) Services.prefs.setIntPref("network.proxy.type", 0); JS
完整的场景示例(匹配你的需求)
把这些代码整合到你的测试流程里,就能实现“代理访问→关闭代理访问→再次开启代理访问”的完整流程:
# 初始化带代理的会话(你的原有代码) Capybara.register_driver :selenium do |app| proxy = Selenium::WebDriver::Proxy.new(http: "127.0.0.1:9999", ssl: "127.0.0.1:9999") desired_caps = Selenium::WebDriver::Remote::Capabilities.firefox({ firefox_profile: "default", proxy: proxy }) Capybara::Selenium::Driver.new(app, {:browser => :firefox, :desired_capabilities => desired_caps}) end Capybara.current_driver = :selenium @session = Capybara::Session.new(:selenium) # 第一步:通过代理访问www.xyz.com @session.visit("https://www.xyz.com") # 第二步:关闭代理,访问www.abc.com @session.driver.browser.execute_script <<-JS Services.prefs.setIntPref("network.proxy.type", 0); JS @session.visit("https://www.abc.com") # 第三步:再次开启代理,访问www.123.com @session.driver.browser.execute_script <<-JS Services.prefs.setIntPref("network.proxy.type", 1); Services.prefs.setCharPref("network.proxy.http", "127.0.0.1"); Services.prefs.setIntPref("network.proxy.http_port", 9999); Services.prefs.setCharPref("network.proxy.ssl", "127.0.0.1"); Services.prefs.setIntPref("network.proxy.ssl_port", 9999); Services.prefs.setBoolPref("network.proxy.share_proxy_settings", true); JS @session.visit("https://www.123.com")
注意事项
- 执行完代理切换的脚本后,记得重新访问目标网址或者刷新当前页面,确保新的代理设置生效
- 这个方法适配绝大多数新版本的Firefox和Geckodriver,如果你遇到兼容性问题,可以检查一下两者的版本是否匹配
- 如果你需要切换不同的代理地址,只需要修改脚本里的代理IP和端口即可
内容的提问来源于stack exchange,提问作者Tikiboy
相关产品推荐
相关产品推荐

