核心代码是:
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"))
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 里看到:
|