首页 > 技术文章 > 无头浏览器适用场景

mmz77-aa 2022-03-03 16:31 原文

我们在使用爬虫语言的时候,不是所有业务场景都必须使用python,有些业务场景可以使用无头浏览器来完成。关于无头浏览器的知识点还是挺多的,今天我们就浅显的讨论一下。因为无头浏览器的一些特性导致和一般的爬虫程序相比,其运行环境要求搭建的工具和库较多,因此如果目标网站反爬不是很难,可以直接通过简单的http请求进行采集。

如果我们访问的目标网站验证的机制比较多复杂,比如需要验证登录、js反爬策略等情况下,建议大家可以使用无头浏览器伪装正常用户,同时配合使用爬虫代理加强版进行数据采集。关于如何配合使用爬虫代理加强版我们简单的示例下:

from selenium import webdriver
    import string
    import zipfile

    # 代理服务器(产品官网 www.16yun.cn)
    proxyHost = "t.16yun.cn"
    proxyPort = "31111"

    # 代理验证信息
    proxyUser = "username"
    proxyPass = "password"

    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'D:/{}_{}@t.16yun.zip'.format(proxy_username, proxy_password)

        manifest_json = """
        {
            "version": "1.0.0",
            "manifest_version": 2,
            "name": "16YUN Proxy",
            "permissions": [
                "proxy",
                "tabs",
                "unlimitedStorage",
                "storage",
                "",
                "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: ["foobar.com"]
                }
              };

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

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

            chrome.webRequest.onAuthRequired.addListener(
                callbackFn,
                {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")

    # 如报错 chrome-extensions 
    # option.add_argument("--disable-extensions")

    option.add_extension(proxy_auth_plugin_path)

    # 关闭webdriver的一些标志
    # option.add_experimental_option('excludeSwitches', ['enable-automation'])        

    driver = webdriver.Chrome(chrome_options=option)

    # 修改webdriver get属性
    # script = '''
    # Object.defineProperty(navigator, 'webdriver', {
    # get: () => undefined
    # })
    # '''
    # driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {"source": script})     



    driver.get("http://httpbin.org/ip")

但是具体使用还是需要根据业务场景的实际需求进行调整,更多关于无头浏览器中使用代理的方式可以咨询这里https://www.16yun.cn/#banner

 
 

推荐阅读