How to change the User Agent using Selenium and Python

13,607

Solution 1

Your code is just perfect. You simply have to write the line of code to change the in the next line. As an example:

  • Code Block:

    from selenium import webdriver
    
    driver = webdriver.Chrome(executable_path=r'C:\WebDrivers\chromedriver.exe')
    print(driver.execute_script("return navigator.userAgent;"))
    # Setting user agent as Chrome/83.0.4103.97
    driver.execute_cdp_cmd('Network.setUserAgentOverride', {"userAgent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36'})
    print(driver.execute_script("return navigator.userAgent;"))
    # Setting user agent as Chrome/83.0.4103.53
    driver.execute_cdp_cmd('Network.setUserAgentOverride', {"userAgent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.53 Safari/537.36'})
    print(driver.execute_script("return navigator.userAgent;"))
    driver.get('https://www.httpbin.org/headers')
    
  • Console Output:

    Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36
    Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36
    Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.53 Safari/537.36
    
  • Browser Snapshot:

useragent


Reference

You can find a couple of relevant detailed discussions in:

Solution 2

You should use driver options:

from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument("user-agent=[user-agent string]")

driver = webdriver.Chrome(executable_path='path', chrome_options=options)
Share:
13,607
Salvatore Timpani
Author by

Salvatore Timpani

Updated on June 04, 2022

Comments

  • Salvatore Timpani
    Salvatore Timpani almost 2 years

    I am having an error when changing the web driver user agent in Python using selenium.

    Here is my code:

    import requests
    import json
    from selenium import webdriver
    from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
    driver = webdriver.Chrome(driver_path) driver.execute_cdp_cmd('Network.setUserAgentOverride', {"userAgent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36'})
    #Error is on line above
    

    Here is my error:

    >>> driver = webdriver.Chrome(driver_path) driver.execute_cdp_cmd('Network.setUserAgentOverride', {"userAgent":"python 3.7", "platform":"Windows"}) 
      File "<stdin>", line 1
        driver = webdriver.Chrome(driver_path) driver.execute_cdp_cmd('Network.setUserAgentOverride', {"userAgent":"python 3.7", "platform":"Windows"})```