python selenium在打开的浏览器中动态调整User Agent
程序员文章站
2022-06-15 13:32:30
核心代码是:browser.execute_cdp_cmd('network.setuseragentoverride', { "useragent": "mozilla/5.0 (wi...
核心代码是:
browser.execute_cdp_cmd('network.setuseragentoverride', { "useragent": "mozilla/5.0 (windows nt 6.3; wow64) applewebkit/537.36 (khtml, like gecko) chrome/41.0.2226.0 safari/537.36", "platform": "windows"})
使用示例:
import time from selenium import webdriver if __name__ == '__main__': option = webdriver.chromeoptions() option.add_argument('lang=zh_cn.utf-8') # 设置 browser = webdriver.chrome(chrome_options=option) browser.get("https://www.baidu.com") print(browser.execute_script("return navigator.useragent")) # 打印当前的useragent # 动态调整useragent time.sleep(3) browser.execute_cdp_cmd('network.setuseragentoverride', { "useragent": "mozilla/5.0 (windows nt 6.3; wow64) applewebkit/537.36 (khtml, like gecko) chrome/41.0.2226.0 safari/537.36", "platform": "windows"}) print(browser.execute_script("return navigator.useragent")) browser.get("https://www.baidu.com")
打印结果:
mozilla/5.0 (macintosh; intel mac os x 10_15_7) applewebkit/537.36 (khtml, like gecko) chrome/97.0.4692.99 safari/537.36
mozilla/5.0 (windows nt 6.3; wow64) applewebkit/537.36 (khtml, like gecko) chrome/41.0.2226.0 safari/537.36
第一行是我的chrome
原始的header,第二行是修改后的header
并且可以在浏览器的header里看到:
到此这篇关于python selenium在打开的浏览器中动态调整user agent的文章就介绍到这了,更多相关python selenium调整user agent内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!