class WebDriver:
def __init__(self, host, port, user, passw):
self.host = host
self.port = port
self.user = user
self.passw = passw
self.manifest_json = """
{
"version": "1.0.0",
"manifest_version": 2,
"name": "Proxy change",
"permissions": [
"proxy",
"tabs",
"unlimitedStorage",
"storage",
"<all_urls>",
"webRequest",
"webRequestBlocking"
],
"background": {
"scripts": ["background.js"]
},
"minimum_chrome_version":"22.0.0"
}
"""
self.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']
);
""" % (self.host, self.port, self.user, self.passw)
def get_chromedriver(self, use_proxy=False, user_agent=None):
path = os.path.dirname(os.path.abspath(__file__))
chrome_options = webdriver.ChromeOptions()
if use_proxy:
pluginfile = 'proxy_auth_plugin.zip'
with zipfile.ZipFile(pluginfile, 'w') as zp:
zp.writestr("manifest.json", self.manifest_json)
zp.writestr("background.js", self.background_js)
chrome_options.add_extension(pluginfile)
if user_agent:
chrome_options.add_argument('--user-agent=%s' % user_agent)
chrome_options.add_experimental_option('excludeSwitches', ['enable-logging']);
driver = webdriver.Chrome(
os.path.join(path, 'chromedriver'),
options=chrome_options)
return driver
我正在尝试制作一个动态更改 webdriver 代理的扩展。基本上我的目标是使用 driver.execute_script(扩展中的函数更改位于 background.js 文件中的代理)函数来更改它。所以这是我的问题:我如何与 background.js 通信,我将能够直接从 webdriver 中的 devtools 控制台使用代理更改功能(driver.execute_script())。