• python+selenium+ Chrome 运行中更换userAgent


    通常情况下用selenium开发爬虫时,会使用以下方式添加UA

    chrome_options.add_argument('user-agent=' + self.ua)

    但是每次更换需要重启浏览器,这会造成资源浪费。好在selenium支持CDP,于是翻了文档终于找到了解决方法。解决方法如下

    driver.execute_cdp_cmd("Emulation.setUserAgentOverride", {
            "userAgent": "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0"
        })

    执行后打开控制台,输入navigator.userAgent查看,会发现userAgent已经改变,访问任何页面都会是目前设置的

    在这里插入图片描述

    同时官方文档中还有以下参数可以使用:

    {
                        "name": "setUserAgentOverride",
                        "description": "Allows overriding user agent with the given string.",
                        "redirect": "Emulation",
                        "parameters": [
                            {
                                "name": "userAgent",
                                "description": "User agent to use.",
                                "type": "string"
                            },
                            {
                                "name": "acceptLanguage",
                                "description": "Browser langugage to emulate.",
                                "optional": true,
                                "type": "string"
                            },
                            {
                                "name": "platform",
                                "description": "The platform navigator.platform should return.",
                                "optional": true,
                                "type": "string"
                            },
                            {
                                "name": "userAgentMetadata",
                                "description": "To be sent in Sec-CH-UA-* headers and returned in navigator.userAgentData",
                                "experimental": true,
                                "optional": true,
                                "$ref": "Emulation.UserAgentMetadata"
                            }
                        ]
                    }
  • 相关阅读:
    条件编译
    宏定义
    联合体,枚举类型
    结构体的概念
    C#程序报找不到时区错误
    C# ArrayList和List的区别
    C# 无法将类型为“__DynamicallyInvokableAttribute”的对象强制转换为类型...
    C# readonly与const区别
    C#特性
    Linux vsftpd 安装配置使用
  • 原文地址:https://www.cnblogs.com/Im-Victor/p/14799098.html
Copyright © 2020-2023  润新知