# 在 Selenium WebDriver 中使用代理（Chrome 与 Firefox）

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


## 方案 1：IP 白名单（推荐用于服务器）

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

```python
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
from seleniumwire import webdriver
from selenium.webdriver.chrome.options import Options

proxy = "http://USER-cc-de-city-berlin-sid-sel1-ttl-30m:PASS@res.proxshift.com: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()
```

> Warn：Selenium Wire 会在本地拦截 TLS 以添加标头，并在它驱动的浏览器中安装自己的证书。此方式适合自动化任务，但不适合任何重视证书完整性的场景。


## Firefox

```python
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 标头。

来源：https://proxshift.com/zh/guides/selenium-proxy
