在Selenium中使用Firefox GeckoDriver配置代理的问题
解决Selenium Firefox代理配置不生效的问题
我看你已经用requests顺利搞定了代理IP的获取和验证,但在Selenium+Firefox这里栽了跟头——明明配置了代理,访问验证网址却还是显示真实IP对吧?其实问题出在你的代理配置不够完整,我给你拆解一下原因和修复方案:
为什么你的配置不生效?
你之前的代码只设置了network.proxy.http和对应的端口,但验证网址是HTTPS协议的(https://api.ipify.org),Firefox默认会对HTTPS请求使用单独的代理配置,没设置的话就会绕过代理直接用真实IP访问。
修复方案:完整的代理配置
方法1:使用传统FirefoxProfile(适用于Selenium 3及部分Selenium 4版本)
把HTTP和HTTPS代理都配置上,同时确保本地地址不绕过代理,完整代码如下:
from selenium import webdriver # 初始化Firefox配置文件 profile = webdriver.FirefoxProfile() # 设置代理模式为手动配置 profile.set_preference("network.proxy.type", 1) # 配置HTTP代理 profile.set_preference("network.proxy.http", "190.186.58.198") profile.set_preference("network.proxy.http_port", 53281) # 关键!配置HTTPS代理(和HTTP代理一致即可,除非你的代理区分协议) profile.set_preference("network.proxy.ssl", "190.186.58.198") profile.set_preference("network.proxy.ssl_port", 53281) # 可选:配置FTP代理(如果需要访问FTP站点) profile.set_preference("network.proxy.ftp", "190.186.58.198") profile.set_preference("network.proxy.ftp_port", 53281) # 禁止本地地址绕过代理(确保所有请求都走代理) profile.set_preference("network.proxy.no_proxies_on", "") # 更新配置并启动浏览器 profile.update_preferences() driver = webdriver.Firefox(firefox_profile=profile) # 访问验证网址测试 driver.get("https://api.ipify.org?format=json")
方法2:使用FirefoxOptions(Selenium 4+推荐方式,FirefoxProfile已被弃用)
新版Selenium更推荐用Options类来配置,写法更简洁,兼容性更好:
from selenium import webdriver from selenium.webdriver.firefox.options import Options options = Options() proxy_ip = "190.186.58.198" proxy_port = 53281 # 基础代理配置 options.set_preference("network.proxy.type", 1) options.set_preference("network.proxy.http", proxy_ip) options.set_preference("network.proxy.http_port", proxy_port) options.set_preference("network.proxy.ssl", proxy_ip) options.set_preference("network.proxy.ssl_port", proxy_port) options.set_preference("network.proxy.no_proxies_on", "") # 启动浏览器并访问验证地址 driver = webdriver.Firefox(options=options) driver.get("https://api.ipify.org?format=json")
额外注意事项
- 确保你使用的代理IP是有效且支持HTTPS的:你之前用requests验证过的代理是有效的,但要确认它是否支持HTTPS协议(有些免费代理只支持HTTP)。
- 如果代理需要用户名密码认证:这种情况需要额外配置,比如使用Firefox代理认证扩展,或者通过设置
network.proxy.socks_username和network.proxy.socks_password(仅适用于SOCKS代理),HTTP/HTTPS代理的认证相对麻烦,通常需要借助扩展实现。
内容的提问来源于stack exchange,提问作者Nimish Bansal
相关产品推荐
相关产品推荐

