【发布时间】:2016-11-04 13:19:18
【问题描述】:
我正在尝试获取 HTML 页面源代码,以便使用 无头浏览器测试 测试 GWT 应用程序 的 GUI。首先我尝试使用 HtmlUnitDriver 获取页面的内容,如下所示:
DesiredCapabilities capabilities = DesiredCapabilities.htmlUnit();
//set an userId header
capabilities.setCapability("id", "userId");
HtmlUnitDriver unitDriver = new HtmlUnitDriver(capabilities);
//enabled javascript
unitDriver.setJavascriptEnabled(true);
unitDriver.get("http://localhost:portNo/example/");
String pageSource = unitDriver.getPageSource();
第二种方法是使用WebClient:
WebClient webClient = new WebClient();
//enabled javascript
webClient.getOptions().setJavaScriptEnabled(true);
//set an userId header
webClient.addRequestHeader("id", "userId");
HtmlPage page = webClient.getPage("http://localhost:portNo/example/");
String contentAsString = page.getWebResponse().getContentAsString();
然而,在这两种情况下,我得到了相同的结果。结果不包含页面的实际内容,它显示如下:
</iframe>
<!-- RECOMMENDED if your web app will not function without JavaScript enabled --> <noscript>
<div style="width: 22em; position: absolute; left: 50%; margin-left: -11em; color: red; background-color: white; border: 1px solid red; padding: 4px; font-family: sans-serif">
Your web browser must have JavaScript enabled
in order for this application to display correctly.
</div>
</noscript>
<iframe src="javascript:''" id="frameId" style="position:absolute;width:0;height:0;border:none" tabindex="-1">
</iframe>
为了获取页面的实际内容,我可以执行/启用什么操作吗?谢谢!
【问题讨论】:
-
unitDriver.getPafeSource() 和 page.getWebReponse() 都在返回主机页面内容(请参阅gwtproject.org/doc/latest/…)。这是实际内容。但我怀疑你想在引导后检查一些元素。在这种情况下,您应该使用来自 HtmlUnit/WebClient 的 DOM 相关 API(例如 page.asText、page.getByXpath)
-
谢谢你的回答,亚历山大。你是对的,我正在页面中寻找 DOM 元素,但问题是,例如,在调用 unitDriver.findElementByClassName("listGrid") 时,我没有从中得到任何东西。另外,page.asText() 方法只提供了页面标题,所以也不是很有用。
标签: java gwt selenium-webdriver webclient htmlunit-driver