HtmlUnit如何在执行Javascript后获取页面 [英] HtmlUnit How to get a page after executing Javascript

查看:464
本文介绍了HtmlUnit如何在执行Javascript后获取页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用HTML单元在网页上运行javascript,以便更改页面.

I'm trying to use Html Unit to run javascript on a webpage in order to change page.

我要导入:

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlDivision;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.ScriptResult;

代码类似于:

String javaScriptCode = "changePage(1)";
try{
    webClient = new WebClient(BrowserVersion.CHROME);
    webClient.getOptions().setCssEnabled(false);
    webClient.getOptions().setJavaScriptEnabled(true);
    page = webClient.getPage(url);
    newPage = page.executeJavaScript(javaScriptCode).getNewPage();
    webClient.close();
} catch (Exception e) {
    e.printStackTrace();
}

但是我得到了错误:

[Java] The method getNewPage() is undefined for the type ScriptResult [67108964]

哪个是非常清晰的,但是并没有告诉我应该使用哪种方法?我在互联网上找到的大多数内容都是基于getNewPage方法或getPage的,但是库中可能已有更改... 请参阅:使用HTMLUnit调用JavaScript函数

Which is crystal clear, however it doesn't tell me wich method I'm supposed to use ? Most of what I found on internet is based on the getNewPage method or on getPage but there may have been changes in the library... see : calling a JavaScript function with HTMLUnit

我正在使用:

<dependency>
  <groupId>net.sourceforge.htmlunit</groupId>
  <artifactId>htmlunit</artifactId>
  <version>2.33</version>
</dependency>

推荐答案

是的,方法2.3.3中删除了getNewPage()方法,这是有关事件处理的大量重构的一部分.

Yes you are right, the method getNewPage() was removed with the version 2.33 as part of a a huge refactoring regarding event handling.

作为替换,您可以使用窗口的所附页面.

As replacement you can use the enclosed page of the window.

例如如果您确定结果页面与当前页面在同一窗口中(已替换页面而不打开新窗口),则可以使用

E.g. if you are sure that the resulting page is in the same window as your current page (has replaced your page without opening a new window), you can use

page.getEnclosingWindow().getEnclosedPage()

如果您的代码可能会打开一个新窗口,则向webClient询问当前窗口会更省钱(新打开的窗口会自动标记为当前窗口)

If your code might opend up a new window it will be more save to ask the webClient for the current window (newly opened windows are automatically marked as the current)

page.getWebClient().getCurrentWindow().getEnclosedPage()

或者在您的代码示例中,您可以直接使用客户端

Or in your code sample you can directly use the client

webClient.getCurrentWindow().getEnclosedPage()

希望有帮助.

这篇关于HtmlUnit如何在执行Javascript后获取页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆