如何在Python3.7+Selenium4+Firefox驱动中设置代理认证用户名密码?
解决Selenium 4 + Firefox 代理用户名密码认证问题
哎,我太懂你这种卡了好几天的崩溃感了!我之前在搭配Selenium 4和Firefox做项目时,也踩过一模一样的代理认证大坑——老方法要么过期失效,要么被Selenium的bug卡得死死的,跟你遇到的情况完全契合:2013年的旧扩展根本用不了、switch_to_alert()因为兼容性问题完全无效、手动创建配置文件还被Firefox限制不让存账号密码。
给你分享几个我亲测有效的解决方案,按省心程度排序:
方法一:用Selenium Wire 自动处理代理认证
Selenium Wire是Selenium的扩展库,专门解决代理相关的痛点,它能自动拦截代理认证请求并注入用户名密码,完全不用管烦人的弹窗。
步骤如下:
- 先安装依赖库:
pip install selenium-wire
- 编写核心代码:
from seleniumwire import webdriver from selenium.webdriver.firefox.options import Options # 替换成你的代理信息 proxy_username = "你的代理用户名" proxy_password = "你的代理密码" proxy_address = "代理地址:端口号" options = Options() # 配置代理参数 seleniumwire_options = { 'proxy': { 'http': f'http://{proxy_username}:{proxy_password}@{proxy_address}', 'https': f'http://{proxy_username}:{proxy_password}@{proxy_address}', 'no_proxy': 'localhost,127.0.0.1' # 可选,排除不需要走代理的本地地址 } } # 启动浏览器 driver = webdriver.Firefox(options=options, seleniumwire_options=seleniumwire_options) # 测试代理是否生效 driver.get("https://httpbin.org/ip") print(driver.page_source) driver.quit()
这个方法最省心,Selenium Wire会全程帮你处理认证环节,完全不用手动操作弹窗,而且完美兼容最新版的Selenium 4和Firefox。
方法二:通过代码修改Firefox配置文件,绕过手动输入限制
你之前说手动创建配置文件不行,是因为Firefox为了安全,默认禁止手动保存代理的明文账号密码,但我们可以通过代码修改配置参数来实现:
- 先手动创建一个Firefox配置文件:打开Firefox,输入
about:profiles,点击「创建新配置文件」,记住生成的配置文件路径。 - 编写代码加载配置并注入认证信息:
from selenium import webdriver from selenium.webdriver.firefox.options import Options import base64 # 替换成你的信息 proxy_username = "你的代理用户名" proxy_password = "你的代理密码" proxy_host = "代理地址" proxy_port = "端口号" profile_path = "你刚才创建的Firefox配置文件路径" options = Options() options.add_argument(f"-profile {profile_path}") # 设置代理服务器地址 options.set_preference("network.proxy.type", 1) options.set_preference("network.proxy.http", proxy_host) options.set_preference("network.proxy.http_port", int(proxy_port)) options.set_preference("network.proxy.ssl", proxy_host) options.set_preference("network.proxy.ssl_port", int(proxy_port)) # 关键:注入认证凭据(用base64编码处理) auth_string = base64.b64encode(f"{proxy_username}:{proxy_password}".encode()).decode() options.set_preference("network.proxy.autoconfig_url", f"data:text/plain,function FindProxyForURL(url, host) {{ return 'PROXY {proxy_host}:{proxy_port};'; }}") options.set_preference("network.proxy.socks_username", proxy_username) options.set_preference("network.proxy.socks_password", proxy_password) # 解除Firefox对认证信息长度的限制 options.set_preference("network.http.phishy-userpass-length", 255) driver = webdriver.Firefox(options=options) driver.get("https://httpbin.org/ip") print(driver.page_source) driver.quit()
这个方法的核心是用PAC脚本指定代理,同时通过配置参数注入认证信息,绕开Firefox的手动输入限制。
为什么你之前的方法会失效?
- 旧扩展:2013年的扩展早就不兼容最新的Firefox版本了,Firefox的扩展机制这些年更新了好几次,旧扩展根本加载不进去。
switch_to_alert():Selenium 4已经弃用了这个方法,而且就算用新的switch_to.alert(),Firefox的代理认证弹窗属于系统级弹窗,不是JS弹窗,Selenium根本捕获不到,这确实是长期存在的兼容性bug。- 手动配置文件:Firefox为了安全,禁止用户手动在配置文件里保存代理的明文账号密码,所以你手动操作根本存不上,必须通过代码修改配置参数。
内容的提问来源于stack exchange,提问作者Fazıl Akbulut
相关产品推荐
相关产品推荐

