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"
                        }
                    ]
                }
复制代码

 

posted @   mingruqi  阅读(1386)  评论(1编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示