1

I am attempting to change my user agent and print the changed user agent to the terminal to check whether it has been successfully changed however I am having no luck.

I am using selenium wire and attempting to change it so i can login to a mobile version of the website. I cant put in the user agent i want due to security reasons however i have been at it for days and have no luck.

Please see my code below

driver = webdriver.Chrome('/Users/callum/Desktop/chromedriver')

def interceptor(request):

del request.headers['User-Agent']

request.headers['User-Agent'] = '####'  

driver.get("https://www.google.com")

I also cannot print the user agent from selenium wire, i can only do it using this method.

agent = driver.execute_script("return navigator.userAgent")

print(agent)

Can someone please assist, it would be much appreciated :)

Callum
  • 231
  • 1
  • 3
  • 12

2 Answers2

4
from seleniumwire import webdriver  # Import from seleniumwire

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"')
browser = webdriver.Chrome(chrome_options=chrome_options)
user_agent = browser.execute_script("return navigator.userAgent;")
print(str(user_agent))
# Go to the Google home page
browser.get('https://www.google.com')

The same Chrome options that are mentioned in this question will also work here. For the printing of user-agent string see this question.

  • Does it have a sense run tests separately under different user_agents when both are mobile plaftorms? same resolution - witdth-height Agents: iOS = "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/603.1.23 (KHTML, like Gecko) Version/10.0 Mobile/14E5239e Safari/602.1" Android = "Mozilla/5.0 (Linux; Android 8.0.0; SM-G960F Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36" – Noro96 Jun 14 '22 at 13:39
  • @Noro96 I'm not sure what you're asking? Do you mean "Is it sensible to run tests under different user_agents when both are on mobile platforms?" It depends on your specific project requirements of course, but I probably would test these different cases, as Mozilla and Chrome are quite different, e.g. Chrome uses Chromium as the majority of source code, whereas Mozilla doesn't. Apologies if I have misunderstood your question. – David Dancey Aug 12 '23 at 11:15
1

Check out the mobile emulation capabilities of the Chrome driver:

https://chromedriver.chromium.org/mobile-emulation

Sergio Pulgarin
  • 869
  • 8
  • 20