Selenium配置代理失效求助:设置后IP查询网站IP未变更
Selenium Firefox代理配置无效问题排查与解决提示
在使用Selenium为Firefox驱动配置代理后,访问https://whatismyipaddress.com/时IP地址未变更,代码实现如下:
from selenium import webdriver from selenium.webdriver.common.proxy import Proxy, ProxyType PROXY = "51.15.78.38" proxy = Proxy({ 'proxyType': ProxyType.MANUAL, 'httpProxy': PROXY, 'ftpProxy': PROXY, 'sslProxy': PROXY, 'noProxy': '' }) driver = webdriver.Firefox(service=FirefoxService(GeckoDriverManager().install()), proxy=proxy) driver.get('https://whatismyipaddress.com/')
解决提示
- 修正代理地址格式:当前仅填写了IP,代理需使用
IP:端口的完整格式(比如51.15.78.38:8080),先确认代理的有效端口号。 - 改用FirefoxOptions配置代理:Selenium的Proxy类在新版Firefox中兼容性有限,推荐通过浏览器偏好设置直接配置,示例代码:
from selenium import webdriver from selenium.webdriver.firefox.service import Service from webdriver_manager.firefox import GeckoDriverManager PROXY = "51.15.78.38:你的端口号" options = webdriver.FirefoxOptions() # 设置手动代理模式 options.set_preference("network.proxy.type", 1) # 配置HTTP代理 options.set_preference("network.proxy.http", PROXY.split(":")[0]) options.set_preference("network.proxy.http_port", int(PROXY.split(":")[1])) # 配置HTTPS代理 options.set_preference("network.proxy.ssl", PROXY.split(":")[0]) options.set_preference("network.proxy.ssl_port", int(PROXY.split(":")[1])) # 取消本地地址不走代理的设置 options.set_preference("network.proxy.no_proxies_on", "") driver = webdriver.Firefox(service=Service(GeckoDriverManager().install()), options=options) driver.get('https://whatismyipaddress.com/')
- 验证代理可用性:先用curl或浏览器手动测试代理能否正常访问目标网站,排除代理失效、需要账号密码认证的情况。若代理需认证,需添加以下配置:
# 配置代理用户名密码 options.set_preference("network.proxy.socks_username", "你的代理用户名") options.set_preference("network.proxy.socks_password", "你的代理密码") # 允许HTTP代理的认证请求 options.set_preference("network.http.phishy-userpass-length", 255)
- 禁用自动代理:确保代码覆盖所有代理相关偏好,避免Firefox自动启用系统代理或其他默认配置。
- 检查版本兼容性:确认Selenium版本与GeckoDriver版本匹配,版本不兼容可能导致配置不生效。
内容的提问来源于stack exchange,提问作者Erfan Aliannezhadi
相关产品推荐
相关产品推荐

