Search code examples
pythonseleniumuser-agent

rotating user agent using Python3 and Selenium 4 chrome


I was wondering if it is possible to rotate between user agents using selenium 4 and Python. My script create multiple chrome windows, but all of them get the same fake user agent. Anyone knows if at this date you can rotate selenium fake user agents between each window it creates ? Thank you in advance!

enter image description here

update : here is my updated code, even with cdp (thanks for the updated answer)i still get the same UA for every windows. Might be something wrong in my code that blocks me ?


Solution

  • You can use something like:

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    from fake_useragent import UserAgent # pip3 install fake_useragent
    from time import sleep
    
    options = Options()
    options.add_argument(f'user-agent={UserAgent().random}')
    driver = webdriver.Chrome(chrome_options=options)
    driver.get("http://www.whatsmyua.info/")
    
    sleep(5)
    
    driver.execute_cdp_cmd("Network.enable", {})
    driver.execute_cdp_cmd("Network.setExtraHTTPHeaders", {"headers": {"User-Agent": f"{UserAgent().random}"}})
    driver.get("http://www.whatsmyua.info/")