Way to change Google Chrome user agent in Selenium?

Question:

I’m trying to figure out a way whereby whenever I open up Chrome via Selenium (in Python) in this particular script, the Chrome page automatically opens up with another user agent selected – in this case, Microsoft Edge Mobile (but I will be accessing it from the desktop).

So, after doing some research, I’ve been able to piece together the following code, which I thought would execute a user-agent switch in Chrome and then open up a new Bing.com page:

from selenium import webdriver 
from selenium.webdriver.chrome.options

import Options opts = Options()
opts.add_argument("user-agent=Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 640 XL LTE) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Mobile Safari/537.36 Edge/12.10166")
driver = webdriver.Chrome(chrome_options=opts)
driver = webdriver.Chrome("D:_")
driver.get("https://www.bing.com/")

However, the code doesn’t seem to be working and stops before opening up the designated webpage. I’m fairly certain the first half of code is off, but I’m not quite sure how. Any and all help would be deeply appreciated.

Asked By: theCrabNebula

||

Answers:

You should use ChromeOptions from selenium.webdriver:

from selenium import webdriver

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--user-agent="Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 640 XL LTE) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Mobile Safari/537.36 Edge/12.10166"')
driver = webdriver.Chrome(chrome_options=chrome_options)

This should work.

Answered By: Tim Woocker

A simple way to use a random User Agent would be using Python’s fake_useragent module as follows :

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from fake_useragent import UserAgent

options = Options()
ua = UserAgent()
userAgent = ua.random
print(userAgent)
options.add_argument(f'user-agent={userAgent}')
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:WebDriversChromeDriverchromedriver_win32chromedriver.exe')
driver.get("https://www.google.co.in")
driver.quit()

Result of 3 consecutive execution is as follows :

  1. First Execution :

    Mozilla/5.0 (Windows NT 4.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36
    
  2. Second Execution :

    Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.517 Safari/537.36
    
  3. Third Execution :

    Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1309.0 Safari/537.17
    
Answered By: undetected Selenium