Server uses User-Agent
string to differentiate between different browsers and devices. Each device + browser combination can have a different name to identify the Browser and its version. Thougth that may not be 100% true in all cases.
In this article we will see how to change the user-agent of different browser when automating them using Selenium
Changing User-Agent in Internet Explorer
Unfortunately there is no good way to change the User-Agent of a IE browser. This is either done through registry or through use of Windows API. GitHub Issue # 759 discussed this possibility and was rejected. So one can use the registry method as discussed here
Changing User-Agent in Chrome
To change the user agent in Chrome, we need to use the ChromeOptions
object and pass it along when start the driver
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument("--user-agent=New User Agent")
driver = webdriver.Chrome(chrome_options=options)
Changing User-Agent in Firefox
User agent can be changed in Firefox using the profile
from selenium import webdriver
profile = webdriver.FirefoxProfile()
binary = FirefoxBinary("/opt/homebrew-cask/Caskroom/firefox/38.0.5/Firefox.app/Contents/MacOS/firefox")
profile.set_preference("general.useragent.override", "New user agent")
driver = webdriver.Firefox(firefox_profile=profile, firefox_binary=binary)
Note: The FirefoxBinary is only needed because I have Firefox installed on a non-default path using Homebrew. For others even the below code should work
from selenium import webdriver
profile = webdriver.FirefoxProfile()
profile.set_preference("general.useragent.override", "New user agent")
driver = webdriver.Firefox(firefox_profile=profile)
Changing User-Agent in PhantomJS
PhantomJS is headless webkit based browser. It is quite fast compared to other browsers as there is no GUI rendering. To change the User-Agent of the same we can use below code
from selenium import webdriver
cap = webdriver.DesiredCapabilities.PHANTOMJS
cap["phantomjs.page.settings.userAgent"] = "New user agent"
driver = webdriver.PhantomJS(desired_capabilities=cap)
Changing User-Agent in Safari (Mac OSX)
Safari driver in Selenium doesn’t give much control on customization of settings for the browser. To do this we need to change the default settings of the browser from Terminal
$ defaults write com.apple.Safari CustomUserAgent "New user agent"
Note: The new user agent will not impact already open Safari browsers and will only impact all new instances of the Safari browser
Reverting the User-Agent for Safari
To revert the user agent back to the normal safari agent we can do the following
$ defaults delete com.apple.Safari CustomUserAgent