How to get userAgent information in Selenium Web driver?


We can get the user Agent information with Selenium webdriver. 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 the execute_script method. Selenium does have a direct method the to get or modify user Agent.

Syntax

a= driver.execute_script("return navigator.userAgent")
print(a)

Example

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
#object of Options class
op = webdriver.ChromeOptions()
#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

Updated on: 01-Feb-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements