我在同一个问题上苦苦挣扎了一个多小时,最后@kenorb 的解决方案救了我。简而言之,您需要添加一个为您进行身份验证的浏览器扩展程序(因为 Selenium 本身不能这样做!)。
以下是它在Chrome和Python上的工作方式:
- 创建一个包含两个文件的 zip 文件proxy.zip :
背景.js
var config = {
mode: "fixed_servers",
rules: {
singleProxy: {
scheme: "http",
host: "YOU_PROXY_ADDRESS",
port: parseInt(YOUR_PROXY_PORT)
},
bypassList: ["foobar.com"]
}
};
chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});
function callbackFn(details) {
return {
authCredentials: {
username: "YOUR_PROXY_USERNAME",
password: "YOUR_PROXY_PASSWORD"
}
};
}
chrome.webRequest.onAuthRequired.addListener(
callbackFn,
{urls: ["<all_urls>"]},
['blocking']
);
不要忘记将YOUR_PROXY_*替换为您的设置。
清单.json
{
"version": "1.0.0",
"manifest_version": 2,
"name": "Chrome Proxy",
"permissions": [
"proxy",
"tabs",
"unlimitedStorage",
"storage",
"<all_urls>",
"webRequest",
"webRequestBlocking"
],
"background": {
"scripts": ["background.js"]
},
"minimum_chrome_version":"22.0.0"
}
将创建的 proxy.zip 添加为扩展
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_extension("proxy.zip")
driver = webdriver.Chrome(executable_path='chromedriver.exe', chrome_options=chrome_options)
driver.get("http://google.com")
driver.close()
而已。对我来说,这就像一个魅力。如果您需要动态创建 proxy.zip 或需要 PHP 示例,请转到原始帖子