为HtmlUnitDriver Selenium设置用户代理

时间:2012-10-12 06:48:48

标签: java selenium selenium-webdriver

如何在Selenium Java中为HtmlUnitDriver设置用户代理属性? 我可以用

为firefox驱动程序设置它
FirefoxProfile ffp = new FirefoxProfile();
ffp.setPreference("general.useragent.override", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; Media Center PC 6.0; InfoPath.3; MS-RTC LM 8; Zune 4.7");
WebDriver driver = new FirefoxDriver(ffp);

有没有办法为HtmlUnitDriver执行此操作? 我试过使用setCapability(“UserAgentName”,“一些UA设置”);但这不起作用。

3 个答案:

答案 0 :(得分:8)

您尝试使用DesiredCapabilities吗?

DesiredCapabilities capabilities = DesiredCapabilities.htmlUnit();
capabilities.setBrowserName(<browser_name>);
capabilities.setPlatform(<platform>);
capabilities.setVersion(<version>);
driver = new HtmlUnitDriver(capabilities);

答案 1 :(得分:4)

HtmlUnitDriver 设置自定义用户代理字符串:

final String USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20160101 Firefox/66.0";

WebDriver driver = new HtmlUnitDriver(new BrowserVersion(
                "Firefox", "5.0 (Windows)", USER_AGENT, 66 //important is 3rd argument
));

有效。我在http://myhttp.info上测试它以从远程服务器获取用户代理

(操作系统:W7,Selenium版本:2.37.1,Java 7u45 x64)

@Test
public void testUserAgent() throws Exception {
    driver.get("http://myhttp.info");
    MyHttpInfoPage myHttpInfoPage = PageFactory.initElements(driver, MyHttpInfoPage.class);
    String userAgent = myHttpInfoPage.getUserAgent(); // @FindBy(xpath = "//td[text()='User agent']/following-sibling::td")
    Assert.assertEquals(userAgent, USER_AGENT);
}

(另见BrowserVersion JavaDoc)

答案 2 :(得分:0)

HtmlUnit对浏览器版本有recently updated their internals。现在要更改设置用户代理字符串的模拟浏览器版本,您必须指定浏览器version功能,例如:

Chrome(默认)

DesiredCapabilities capabilities = DesiredCapabilities.htmlUnit();
capabilities.setVersion(org.openqa.selenium.remote.BrowserType.CHROME);
WebDriver myDriver = new HtmlUnitDriver(capabilities);

Internet Explorer

DesiredCapabilities capabilities = DesiredCapabilities.htmlUnit();
capabilities.setVersion(org.openqa.selenium.remote.BrowserType.IE);
WebDriver myDriver = new HtmlUnitDriver(capabilities);

Firefox(未指定firefox版本,默认为52)

DesiredCapabilities capabilities = DesiredCapabilities.htmlUnit();
capabilities.setVersion(org.openqa.selenium.remote.BrowserType.FIREFOX);
WebDriver myDriver = new HtmlUnitDriver(capabilities);

Firefox(指定两个可用版本之一:45或52)

DesiredCapabilities capabilities = DesiredCapabilities.htmlUnit();
// specify ff version 45
capabilities.setVersion(org.openqa.selenium.remote.BrowserType.FIREFOX + "-45");
// ...or specify ff version 52
capabilities.setVersion(org.openqa.selenium.remote.BrowserType.FIREFOX + "-52");
WebDriver myDriver = new HtmlUnitDriver(capabilities);

以上是所有可用版本as of today

要验证它们是否已更改,请检查their master branch