示例代码

from selenium import webdriver
import string
import zipfile

proxyHost = "dyn.horocn.com"
proxyPort = "50000"

# 隧道代理订单号
proxyUser = "xxx"
# 密码,在用户中心 -- 隧道代理订单页面可查询到
proxyPass = "xxx"

def create_proxy_auth_extension(proxy_host, proxy_port,
                               proxy_username, proxy_password,
                               scheme='http', plugin_path=None):
    if plugin_path is None:
        # 请保证下面的路径可用
        plugin_path =  r'/tmp/qtproxy-tunnel-ext.zip'

    manifest_json = """
    {
        "version": "1.0.1",
        "manifest_version": 2,
        "name": "Qtproxy(proxy.horocn.com)",
        "permissions": [
            "proxy",
            "tabs",
            "unlimitedStorage",
            "storage",
            "<all_urls>",
            "webRequest",
            "webRequestBlocking"
        ],
        "background": {
            "scripts": ["background.js"]
        },
        "minimum_chrome_version":"22.0.0"
    }
    """

    background_js = string.Template(
        """
        var config = {
            mode: "fixed_servers",
            rules: {
                singleProxy: {
                    scheme: "${scheme}",
                    host: "${host}",
                    port: parseInt(${port})
                },
                bypassList: ["localhost"]
            }
          };

        chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});

        function callbackFn(details) {
            return {
                authCredentials: {
                    username: "${username}",
                    password: "${password}"
                }
            };
        }

        chrome.webRequest.onAuthRequired.addListener(
                    callbackFn,
                    {urls: ["<all_urls>"]},
                    ['blocking']
        );
        """
    ).substitute(
        host=proxy_host,
        port=proxy_port,
        username=proxy_username,
        password=proxy_password,
        scheme=scheme,
    )

    with zipfile.ZipFile(plugin_path, 'w') as zp:
        zp.writestr("manifest.json", manifest_json)
        zp.writestr("background.js", background_js)

    return plugin_path

proxy_auth_plugin_path = create_proxy_auth_extension(
    proxy_host=proxyHost,
    proxy_port=proxyPort,
    proxy_username=proxyUser,
    proxy_password=proxyPass)

option = webdriver.ChromeOptions()

option.add_argument("--start-maximized")
option.add_extension(proxy_auth_plugin_path)

# 请修改为正确的 chromdriver 路径
# 通过淘宝的镜像地址,可以快速下载 chromedriver:http://npm.taobao.org/mirrors/chromedriver/
driver = webdriver.Chrome("/path/to/chromedriver", chrome_options=option)

# 目标地址,将下面的地址改为你要采集的地址即可
driver.get("https://www.baidu.com")


常见错误

错误一:unknown error: failed to wait for extension background page to load

解决:Chrome 的 headless 模式下不支持加载扩展,删除类似 option.add_argument("--headless") 的配置。通过 Xvfb 可实现类似 Chrome headless 模式的效果。
1、安装 Xvfb:sudo dnf install xorg-x11-server-Xvfb
2、通过 xvfb 启动 Chrome:xvfb-run google-chrome --remote-debugging-port=9222 --disable-gpu https://www.baidu.com
3、通过 chrome-remote-interface 截图
参考:Is it possible to run Google Chrome in headless mode with extensions?

测试环境

  • 操作系统:macOS Mojave
  • Chrome 浏览器:86.0.4240
  • Python:3.8.5

注意

  • 请替换上面的路径为你本地合适的路径,如:plugin_path、chromedriver path
  • 请记得修改上面的用户名和密码

转载请注明