Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the user agent using selenium webdriver in Java

Can someone pls tell me how to switch the user agent using webdriver in Java? I tried below, but getting errors.

FirefoxProfile ffp = new FirefoxProfile(); 
ffp.setPreference("general.useragent.override",
"Mozilla/5.0 (Windows NT 6.1; rv:15.0) Gecko/20100101 Firefox/15.0");
WebDriver fd = new FirefoxDriver(ffp);
like image 593
Srikanth Nakka Avatar asked Aug 28 '13 09:08

Srikanth Nakka


3 Answers

DesiredCapabilities would help you to change user agent.

You can achieve this by calling these methods:

  • setBrowserName(java.lang.String browserName)
  • setPlatform(Platform platform)
  • setVersion(java.lang.String version)

Or

  • static DesiredCapabilities chrome()
  • static DesiredCapabilities firefox()
  • static DesiredCapabilities iphone()
  • ...

More here.

like image 112
M. Abbas Avatar answered Sep 28 '22 11:09

M. Abbas


I believe this solution is the desired answer to the question. I tested it and it worked for me. Happy coding!

FirefoxOptions options = new FirefoxOptions();
String userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36 OPR/60.0.3255.170";
options.addPreference("general.useragent.override",userAgent);

WebDriver webDriver = new FirefoxDriver(options);
webDriver.get("http://whatsmyuseragent.org");
like image 44
Adam Ziegler Avatar answered Sep 28 '22 11:09

Adam Ziegler


I needed to do it for Chrome, and needed to set a specific string (not fitting as platform, browser or version) for Googlebot.

    // import org.openqa.selenium.chrome.ChromeOptions;

    ChromeOptions options = new ChromeOptions();
    options.addArguments("user-agent=\"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)\"");
    new ChromeDriver(options);
like image 40
Mahdi Avatar answered Sep 28 '22 10:09

Mahdi