Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting User Agent for HtmlUnitDriver Selenium

How do I set the user agent property for HtmlUnitDriver in Selenium Java ? I can set it for the firefox driver with

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

Is there a way to do this for HtmlUnitDriver ? I've tried to use the setCapability("UserAgentName", "some UA settings"); but this does not work.

like image 839
Jeffrey Chen Avatar asked Oct 12 '12 06:10

Jeffrey Chen


2 Answers

Did you try using DesiredCapabilities?

DesiredCapabilities capabilities = DesiredCapabilities.htmlUnit();
capabilities.setBrowserName(<browser_name>);
capabilities.setPlatform(<platform>);
capabilities.setVersion(<version>);
driver = new HtmlUnitDriver(capabilities);
like image 72
aradhak Avatar answered Oct 18 '22 12:10

aradhak


Setting custom User Agent string for 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
));

    

It works. I tested it on http://myhttp.info for getting user agent from remote server

(OS: W7, Selenium version: 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);
}

(see also BrowserVersion JavaDoc)

like image 29
Lukas M. Avatar answered Oct 18 '22 14:10

Lukas M.