How to change user agent for Selenium driver?

SeleniumAutomation TestingTesting Tools

We can change the user Agent for Selenium webdriver. The user Agent header has a particular string that provides the network protocol along with the details of operating system, software version, application, and so on.

Selenium does have the ability to get or modify user Agent. This is done with the help of the JavaScript Executor. Selenium executes JavaScript commands with the help of the execute_script method.

To obtain the user Agent information, we have to pass the return navigator.userAgent parameter to that method. To change the user Agent, we shall take the help of ChromeOptions class.

Then apply the add_argument method on the object created. We shall pass user-agent and <value of the user Agent> as parameters to that method. Finally, this information shall be passed to the driver object.

Syntax

op = webdriver.ChromeOptions()
op.add_argument("user-agent=<user agent value>")

Example

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
#object of Options class
op = webdriver.ChromeOptions()
#add user Agent
op.add_argument
("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
+"AppleWebKit/537.36 (KHTML, like Gecko)"
+"Chrome/87.0.4280.141 Safari/537.36")
#set chromedriver.exe path
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe",
options=op)
#maximize browser
driver.maximize_window()
#launch URL
driver.get("https://www.seleniumhq.org/download/");
#get user Agent with execute_script
a= driver.execute_script("return navigator.userAgent")
print("User agent:")
print(a)
#close browser session
driver.quit()

Output

raja
Published on 01-Feb-2021 17:12:09
Advertisements