python selenium调整User Agent
呆萌的代Ma 人气:0核心代码是:
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里看到:
加载全部内容