You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Selenium配置Firefox代理不生效显示真实IP解决方法

Selenium Firefox代理配置失效问题排查与修复

现有代码的问题

  • 核心问题是Selenium 4.0及以上版本废弃了直接向Firefox构造函数传入proxy参数的写法,旧版Proxy类的配置不会被高版本geckodriver和Firefox浏览器识别,导致代理配置直接失效,浏览器默认走直连,所以会显示真实IP。
  • 次要问题:如果你的代理是SOCKS类型,仅配置http/https/ftp代理字段不会生效,Firefox会忽略不匹配的代理配置走直连;如果代理本身无法连通,也会触发降级直连逻辑。

正确配置方案

方案1:适配Selenium 4.x的标准写法(推荐,稳定性最高)

通过Firefox Options直接配置浏览器内置的代理参数,兼容性最好,不受Proxy类版本变动影响:

from selenium import webdriver
from selenium.webdriver.firefox.options import Options

proxy_ip = "192.156.1.1"
proxy_port = 33
url = 'http://www.expressvpn.com/what-is-my-ip'
driver_path = 'C:\\Users\\user\\geckodriver.exe'

# 初始化配置对象
firefox_options = Options()
# 设置HTTP代理
firefox_options.set_preference("network.proxy.type", 1)
firefox_options.set_preference("network.proxy.http", proxy_ip)
firefox_options.set_preference("network.proxy.http_port", proxy_port)
# 设置HTTPS代理
firefox_options.set_preference("network.proxy.ssl", proxy_ip)
firefox_options.set_preference("network.proxy.ssl_port", proxy_port)
# 设置FTP代理
firefox_options.set_preference("network.proxy.ftp", proxy_ip)
firefox_options.set_preference("network.proxy.ftp_port", proxy_port)
# 配置不走代理的地址,留空表示所有流量都走代理
firefox_options.set_preference("network.proxy.no_proxies_on", "")
# 禁用代理缓存避免旧配置干扰
firefox_options.set_preference("browser.cache.disk.enable", False)
firefox_options.set_preference("browser.cache.memory.enable", False)

# 启动浏览器
browser = webdriver.Firefox(executable_path=driver_path, options=firefox_options)
browser.get(url)

如果是SOCKS5代理,替换上面的代理配置部分为:

firefox_options.set_preference("network.proxy.type", 1)
firefox_options.set_preference("network.proxy.socks", proxy_ip)
firefox_options.set_preference("network.proxy.socks_port", proxy_port)
firefox_options.set_preference("network.proxy.socks_version", 5)
# 让DNS请求也走代理,避免DNS泄露真实IP
firefox_options.set_preference("network.proxy.socks_remote_dns", True)

方案2:Selenium 3.x兼容写法

如果仍在使用Selenium 3.x版本,需要调整Proxy类的参数传递方式:

from selenium import webdriver
from selenium.webdriver.common.proxy import Proxy, ProxyType

proxy = Proxy({
    'proxyType': ProxyType.MANUAL,
    'httpProxy': '192.156.1.1:33',
    'ftpProxy': '192.156.1.1:33',
    'sslProxy': '192.156.1.1:33',
    'noProxy': ''
})
capabilities = webdriver.DesiredCapabilities.FIREFOX
proxy.add_to_capabilities(capabilities)

driver_path = 'C:\\Users\\user\\geckodriver.exe'
browser = webdriver.Firefox(executable_path=driver_path, desired_capabilities=capabilities)
browser.get('http://www.expressvpn.com/what-is-my-ip')

额外验证事项

  • 先确认代理本身可用:可以通过本地curl命令curl -x 192.156.1.1:33 http://icanhazip.com验证代理是否能正常返回代理IP
  • 如果代理需要账号密码认证,需要额外安装火狐代理认证插件,或通过配置浏览器的用户首选项注入认证信息,直接配置IP端口无法生效

内容的提问来源于stack exchange,提问作者Slartibartfast

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 22:36:04