python selenium在打开的浏览器中动态调整User Agent
时间:2023-03-09 12:09:50|栏目:Python代码|点击: 次
核心代码是:
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代码
本文标题:python selenium在打开的浏览器中动态调整User Agent
本文地址:http://www.codeinn.net/misctech/227153.html