核心代码是:
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.setUs编程客栈erAgentOverride', { "userAgent": "Mozilla/5.0 (Windows NT 6.3;http://www.cppcns.com WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2226.0 Safari/537.36", "platform": "Windows"}) print(browser.execute_script("return navigator.userAgent")) brows编程客栈er.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
Moz编程客栈ijXckWlla/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内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
精彩评论