towi_parallelism
towi_parallelism

Reputation: 1481

Change browser type and version using Selenium

I am using the code below to change my user agent using the Selenium Webdriver. However, I can see that Google analytics can easily detect my browser and even its version every time (Firefox 54.0 in this case). Tried it with Chromedriver as well. Same result.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from fake_useragent import UserAgent

useragent = ua.random

#Chrome
'''
opts.add_argument('"'+useragent+'"')
driver =  webdriver.Chrome(chrome_options=opts)
'''

#Firefox
profile = webdriver.FirefoxProfile()
profile.set_preference("general.useragent.override", useragent)
driver = webdriver.Firefox(profile)
driver.get("www.mywebsite.com")

How can I change the user agent properly?

Upvotes: 2

Views: 2783

Answers (1)

undetected Selenium
undetected Selenium

Reputation: 193298

Here is the Answer to your Question:

Considering your aim is to change the User Agent using the Selenium Webdriver, you can use the code block below to access a website every time with a random User Agent using FirefoxProfile:

from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from fake_useragent import UserAgent

binary = FirefoxBinary('C:\\Program Files\\Mozilla Firefox\\firefox.exe')
useragent = UserAgent()
profile = webdriver.FirefoxProfile()
profile.set_preference("general.useragent.override", useragent.random)
driver = webdriver.Firefox(firefox_profile=profile, firefox_binary=binary, executable_path="C:\\Utility\\BrowserDrivers\\geckodriver.exe")
driver.get("http://www.whatsmyua.info/")

Observation

On three different runs the User Agents generated were:

  1. Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:21.0) Gecko/20130331 Firefox/21.0
  2. Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36
  3. Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko

Let me know if this Answers your Question.

Upvotes: 1

Related Questions