集成 · 中级

在 Selenium WebDriver 中使用代理(Chrome 与 Firefox)

Selenium 的典型难题是身份验证:浏览器会显示 WebDriver 无法填写的凭据提示框。两种简洁方案是将服务器加入白名单,或让 Selenium Wire 注入凭据。

阅读约需 2 分钟 4 个章节 更新于 发布于

在控制面板中将服务器的公网 IPv4 添加到白名单。此后 Chrome 只需要代理地址,不会再显示提示框。其限制是:未收到身份验证质询的浏览器不会发送用户名,因此网关无法读取目标定位参数,而会使用账号的默认代理池。若每个会话都需要独立的国家/地区或粘性 ID,请使用方案 2。

Python、Chrome、已加入白名单的服务器
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

opts = Options()
opts.add_argument("--proxy-server=http://res.proxshift.com:9000")
opts.add_argument("--headless=new")
driver = webdriver.Chrome(options=opts)
driver.get("https://api.ipify.org")
print(driver.find_element("tag name", "body").text)
driver.quit()

方案 2:Selenium Wire(用户名、密码和参数)#

Selenium Wire 会运行一个本地代理并代你添加凭据,因此包含全部参数的 ProxShift URL 无需修改即可使用。

Python、Selenium Wire
from seleniumwire import webdriver
from selenium.webdriver.chrome.options import Options

proxy = "http://USER-cc-de-city-berlin-sid-sel1-ttl-30m:[email protected]:9000"
sw_options = {"proxy": {"http": proxy, "https": proxy, "no_proxy": "localhost,127.0.0.1"}}

opts = Options()
opts.add_argument("--headless=new")
driver = webdriver.Chrome(seleniumwire_options=sw_options, options=opts)
driver.get("https://api.ipify.org")
print(driver.find_element("tag name", "body").text)
driver.quit()

Firefox#

Python、Firefox
from selenium import webdriver
from selenium.webdriver.firefox.options import Options

opts = Options()
opts.set_preference("network.proxy.type", 1)
opts.set_preference("network.proxy.http", "res.proxshift.com")
opts.set_preference("network.proxy.http_port", 9000)
opts.set_preference("network.proxy.ssl", "res.proxshift.com")
opts.set_preference("network.proxy.ssl_port", 9000)
opts.set_preference("media.peerconnection.enabled", False)  # 防止 WebRTC 泄漏
driver = webdriver.Firefox(options=opts)  # 服务器已加入白名单,无提示框

实用规则#

  • 每个会话 ID 使用一个 driver;driver 会保持连接,因此在会话有效期结束前,出口始终不变。
  • 在 Chrome 中使用 --headless=new;旧版无头模式具有很容易识别的指纹。
  • 将浏览器语言和时区设置为出口所在国家/地区;Selenium Wire 也可以重写 Accept-Language

大家常问的问题#

使用 Selenium 时,Chrome 为什么会显示代理登录提示框?

WebDriver 没有可用于响应代理身份验证对话框的 API。请将你的 IP 加入白名单以免出现提示框,或运行 Selenium Wire,让它代你注入 Proxy-Authorization 标头。

准备好即可开始

立即投入实际使用。

创建账户,充值 $20,然后将本指南中的端点粘贴到您的工具中。您购买的流量永不过期。