随笔 - 82  文章 - 2 评论 - 1 阅读 - 28932
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

前几天在一个叫【进击的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还有很多的使用方式在添加代理的过程比较复杂,需要多多的学习。以后会分享更多的爬虫知识,感兴趣的可以关注大家交流下学习经验。

 
 
posted on   小橙子11  阅读(5030)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
点击右上角即可分享
微信分享提示