selenium代理IP验证用户名密码方法详解

默认情况下,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: [""]},
        ['blocking']
);

第二步:新建 manifest.json 文件,复制如下代码

{
    "version": "1.0.0",
    "manifest_version": 2,
    "name": "Chrome Proxy",
    "permissions": [
        "proxy",
        "tabs",
        "unlimitedStorage",
        "storage",
        "",
        "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('插件名字')

如果你不想自己总结,我已经封装好代码,直接下载调用即可,下载地址:https://download.csdn.net/download/luzaofa/11357863

你可能感兴趣的:(selenium代理IP验证用户名密码方法详解)