使用Java中的selenium webdriver更改用户代理

时间:2013-08-28 09:37:06

标签: java selenium webdriver selenium-webdriver

有人可以告诉我如何在Java中使用webdriver切换用户代理吗? 我在下面尝试过,但收到错误。

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);

3 个答案:

答案 0 :(得分:7)

DesiredCapabilities可以帮助您更改用户代理。

您可以通过调用以下方法来实现此目的:

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

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

更多here

答案 1 :(得分:1)

我相信此解决方案是该问题的理想答案。我对其进行了测试,并且对我有用。编码愉快!

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");

答案 2 :(得分:0)

我需要针对Chrome浏览器执行此操作,并且需要为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);