在 Java 中使用 selenium webdriver 更改用户代理
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18484317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Changing the user agent using selenium webdriver in Java
提问by Srikanth Nakka
Can someone pls tell me how to switch the user agent using webdriver in Java? I tried below, but getting errors.
有人可以告诉我如何在 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);
采纳答案by M. Abbas
DesiredCapabilitieswould help you to change user agent.
DesiredCapabilities将帮助您更改用户代理。
You can achieve this by calling these methods:
您可以通过调用这些方法来实现这一点:
setBrowserName(java.lang.String browserName)
setPlatform(Platform platform)
setVersion(java.lang.String version)
setBrowserName(java.lang.String browserName)
setPlatform(Platform platform)
setVersion(java.lang.String version)
Or
或者
static DesiredCapabilities chrome()
static DesiredCapabilities firefox()
static DesiredCapabilities iphone()
- ...
static DesiredCapabilities chrome()
static DesiredCapabilities firefox()
static DesiredCapabilities iphone()
- ...
More here.
更多在这里。
回答by Adam Ziegler
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");
回答by Mahdi
I needed to do it for Chrome, and needed to set a specific string (not fitting as platform, browser or version) for Googlebot.
我需要为 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);