如何在Python Selenium中为Firefox浏览器配置使用代理?
Selenium Python 配置Firefox无验证代理方案
以下是针对8080端口无身份验证代理的配置方法,兼容主流Selenium版本:
配置步骤(推荐Selenium 4+版本写法)
- 导入依赖模块
from selenium import webdriver from selenium.webdriver.firefox.options import Options
- 配置代理参数
firefox_options = Options() # 替换为实际代理IP,本地代理默认填127.0.0.1即可 PROXY_HOST = "127.0.0.1" PROXY_PORT = 8080 # 开启手动代理配置 firefox_options.set_preference("network.proxy.type", 1) # 配置HTTP代理 firefox_options.set_preference("network.proxy.http", PROXY_HOST) firefox_options.set_preference("network.proxy.http_port", PROXY_PORT) # 配置HTTPS代理 firefox_options.set_preference("network.proxy.ssl", PROXY_HOST) firefox_options.set_preference("network.proxy.ssl_port", PROXY_PORT) # 可选:配置不需要走代理的地址 firefox_options.set_preference("network.proxy.no_proxies_on", "localhost, 127.0.0.1")
- 初始化浏览器并验证
driver = webdriver.Firefox(options=firefox_options) # 访问IP查询接口验证代理是否生效 driver.get("https://icanhazip.com") print("当前出口IP:", driver.page_source.strip()) # 关闭浏览器 driver.quit()
旧版本Selenium 3兼容写法
如果使用Selenium 3版本,可通过FirefoxProfile实现相同效果:
from selenium import webdriver profile = webdriver.FirefoxProfile() profile.set_preference("network.proxy.type", 1) profile.set_preference("network.proxy.http", "127.0.0.1") profile.set_preference("network.proxy.http_port", 8080) profile.set_preference("network.proxy.ssl", "127.0.0.1") profile.set_preference("network.proxy.ssl_port", 8080) driver = webdriver.Firefox(firefox_profile=profile)
注意:代理IP如果是远程服务器地址,直接修改PROXY_HOST为对应IP即可,无需额外配置验证参数。
内容的提问来源于stack exchange,提问作者JohnnyPhinn
相关产品推荐
相关产品推荐

