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" } ] }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库