原文链接:How to override basic authentication in selenium2 with Java using chrome driver? - Stack Overflow
实现原理,通过扩展程序的方式来设置HTTP代理
from selenium.webdriver import Chrome, ChromeOptions
import zipfile
def use_http():
PROXY_HOST = '113.89.3.***' # rotating proxy or host
PROXY_PORT = 5375 # port
PROXY_USER = '*****' # username
PROXY_PASS = '*****' # password
manifest_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"
}
"""
background_js = """
var config = {
mode: "fixed_servers",
rules: {
singleProxy: {
scheme: "http",
host: "%s",
port: parseInt(%s)
},
bypassList: ["localhost"]
}
};
chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});
function callbackFn(details) {
return {
authCredentials: {
username: "%s",
password: "%s"
}
};
}
chrome.webRequest.onAuthRequired.addListener(
callbackFn,
{urls: ["<all_urls>"]},
['blocking']
);
""" % (PROXY_HOST, PROXY_PORT, PROXY_USER, PROXY_PASS)
pluginfile = 'proxy_auth_plugin.zip'
with zipfile.ZipFile(pluginfile, 'w') as zp:
zp.writestr("manifest.json", manifest_json)
zp.writestr("background.js", background_js)
chrome_options = webdriver.ChromeOptions()
chrome_options.add_extension(pluginfile)
driver = webdriver.Chrome(options=chrome_options)
driver.get('https://httpbin.org/ip')
input()