Python中如何使用selenium配置Firefox的IP代理?

from selenium import webdriver

proxy = ‘117.36.103.170:8118’ chrome_options = webdriver.ChromeOptions() chrome_options.add_argument(’–proxy-server=http://’ + proxy) chrome = webdriver.Firefox(chrome_options=chrome_options) chrome.get(‘http://httpbin.org/get’)

我参照上面的 Chrome 的配置方法,修改成以下的 Firefox 配置,为何没有成功?是不是哪里错了?求解答

from selenium import webdriver

proxy = ‘117.36.103.170:8118’ firefox_options = webdriver.FirefoxOptions() firefox_options.add_argument(’–proxy-server=http://’ + proxy) firefox = webdriver.Firefox(firefox_options=firefox_options) firefox.get(‘http://httpbin.org/get’)


Python中如何使用selenium配置Firefox的IP代理?

4 回复
from selenium import webdriver
from selenium.webdriver.firefox.options import Options

# 配置代理设置
proxy_host = "127.0.0.1"  # 代理服务器地址
proxy_port = "8080"        # 代理端口号

# 创建Firefox配置选项
options = Options()

# 设置代理配置
options.set_preference("network.proxy.type", 1)  # 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)  # HTTPS代理
options.set_preference("network.proxy.ssl_port", int(proxy_port))
options.set_preference("network.proxy.ftp", proxy_host)   # FTP代理
options.set_preference("network.proxy.ftp_port", int(proxy_port))
options.set_preference("network.proxy.socks", proxy_host) # SOCKS代理
options.set_preference("network.proxy.socks_port", int(proxy_port))

# 设置代理对所有协议生效
options.set_preference("network.proxy.share_proxy_settings", True)

# 如果需要认证,添加以下配置
# options.set_preference("network.proxy.username", "your_username")
# options.set_preference("network.proxy.password", "your_password")

# 创建驱动时传入配置
driver = webdriver.Firefox(options=options)

# 测试代理是否生效
try:
    driver.get("http://httpbin.org/ip")
    print("当前页面源代码(包含IP信息):")
    print(driver.page_source[:500])  # 打印前500字符
except Exception as e:
    print(f"访问出错: {e}")
finally:
    driver.quit()

核心是通过options.set_preference()设置Firefox的代理参数,其中network.proxy.type=1启用手动代理,然后分别配置各协议的代理地址和端口。

如果要用带认证的代理,取消注释username/password那两行并填上你的凭证。测试时建议用httpbin.org/ip来验证代理是否生效。

简单说就是通过Firefox的preference配置项来设置代理。

谢谢,已参照其中的方法改写成 Python 代码

Python | Firefox IP 代理 - 灵魂的文章 - 知乎
https://zhuanlan.zhihu.com/p/39281522

回到顶部