【问题标题】:Cannot enable javascript for GWT application using Selenium WebClient or HtmlUnitDriver无法使用 Selenium WebClient 或 HtmlUnitDriver 为 GWT 应用程序启用 javascript
【发布时间】: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>

      &lt;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"&gt;
        Your web browser must have JavaScript enabled
        in order for this application to display correctly.
      &lt;/div&gt;

    </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


【解决方案1】:

通过设置超时以加载 javascript 文件来解决问题。

所以,在这样做之后:

HtmlPage page = webClient.getPage("http://localhost:portNo/example/");
webClient.waitForBackgroundJavaScript(10000); //time in milliseconds

页面有内容,我可以找到预期的 DOM 元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-20
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多