【问题标题】:Changing the user agent using selenium webdriver in Java在 Java 中使用 selenium webdriver 更改用户代理
【发布时间】:2013-08-28 09:37:06
【问题描述】:

谁能告诉我如何在 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);

【问题讨论】:

  • 你遇到了什么错误?
  • 什么语法错误?你能分享错误的消息文本吗?
  • 它说的是哪一行?

标签: java selenium webdriver selenium-webdriver


【解决方案1】:

DesiredCapabilities 将帮助您更改用户代理。

您可以通过调用这些方法来实现:

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

或者

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

更多here.

【讨论】:

  • 嘿,两个链接似乎都已更改。你能更新一下吗?
【解决方案2】:

我相信这个解决方案是问题的理想答案。我测试了它,它对我有用。编码愉快!

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

【讨论】:

    【解决方案3】:

    我需要为 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);
    

    【讨论】:

      猜你喜欢
      • 2019-08-12
      • 2014-01-19
      • 2017-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多