python selenium在打開的瀏覽器中動態調整User Agent

核心代碼是:

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內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: