selenium添加代理IP簡單教程


前幾天在一個叫【進擊的python】的爬蟲群里,有個同學問了一個關於Python中selenium如何添加代理IP的問題,這里拿出來給大家分享下,一起學習。

對於很多做爬蟲的同學來說這個問題非常的簡單,任何爬蟲語言都可以加上代理ip去采集數據,但是有細微的差別,對python使用代理ip有研究的可以去這里了解下https://www.16yun.cn/。關於在selenium中加代理我們給大家示例下:

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")

雖然添加代理都是初學爬蟲的知識,但是selenium還有很多的使用方式在添加代理的過程比較復雜,需要多多的學習。以后會分享更多的爬蟲知識,感興趣的可以關注大家交流下學習經驗。

 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM