我试图获得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>
是否有什么我可以做/启用,以获得页面的实际内容?谢谢你!
通过设置一个超时来解决这个问题,以便javascript文件加载。
那么,这样做之后:
HtmlPage page = webClient.getPage("http://localhost:portNo/example/");
webClient.waitForBackgroundJavaScript(10000); //time in milliseconds
页面有内容,我可以找到所需的DOM元素。