• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

HtmlUnit在执行Javascript后获取页面

用户头像
it1352
帮助1

问题说明

我正在尝试使用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>

正确答案

#1

是的,方法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()

希望有帮助.

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfjeci
系列文章
更多 icon
同类精品
更多 icon
继续加载