默认情况下,Chrome的–proxy-server="http://ip:port"参数不支持设置用户名和密码认证。但在启动代理IP时大多数会遇到需要通过用户名和密码验证来添加代理,本博客就遇到了这样的问题,查阅资料后,对整个思路做了一个封装,与大家共勉
第一步:新建 background.js 文件,复制如下代码
var config = {
mode: "fixed_servers",
rules: {
singleProxy: {
scheme: "http",
host: "mimvp_proxy_host",
port: parseInt(mimvp_proxy_port)
},
bypassList: ["mimvp.com"]
}
};
chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});
function callbackFn(details) {
return {
authCredentials: {
username: "mimvp_username",
password: "mimvp_password"
}
};
}
chrome.webRequest.onAuthRequired.addListener(
callbackFn,
{urls: ["<all_urls>"]},
['blocking']
);
第二步:新建 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"
}
第二步:创建一个 Chrome-proxy-helper 文件夹,将 background.js 和 manifest.json 放入其中
第三步:插件制作
# 创建一个zip文件
zf = zipfile.ZipFile(extension_file_path, mode='w')
zf.write(os.path.join(cls.CHROME_PROXY_HELPER_DIR, 'manifest.json'), 'manifest.json')
# 替换模板中的代理参数,生成插件
background_content = open(os.path.join(cls.CHROME_PROXY_HELPER_DIR, 'background.js')).read()
background_content = background_content.replace('%proxy_host', ip)
background_content = background_content.replace('%proxy_port', port)
background_content = background_content.replace('%username', username)
background_content = background_content.replace('%password', password)
zf.writestr('background.js', background_content)
zf.close()
第四步:通过 options.add_extension() 方法将生成的插件传入即可
options.add_extension('插件名字')