如何在 Java 中使用 WebKit 从加载页面获取 html

How to obtain html from loaded page using WebKit in Java

我的目标是使用 Java 解析 Airbnb 房源页面,例如这个: https://www.airbnb.com/rooms/28149735

我第一次尝试使用 JSoup 如下:

String html = Jsoup.connect(webPage).get().html();

但是它不起作用,因为它无法加载页面的脚本,也不会呈现我从 Chrome 或 Firefox 等浏览器检查加载页面时看到的内容。

所以我现在尝试使用 WebKit,代码如下:

// get the instance of the webkit
BrowserEngine browser = BrowserFactory.getWebKit();
Page page = browser.navigate("https://www.airbnb.com/rooms/28149735");
page.show();

String html = page.getDocument().getBody().getInnerHTML();

但这也不起作用:页面正确加载(我在控制台的日志中看到它,弹出窗口正确显示),但是一旦我加载了页面,我就无法访问 html(我得到一个空指针异常,错误日志见下文)。

当我在调试模式下 运行 代码时,我查看了页面对象,该页面中的文档显示为 "null",这似乎造成了错误。

所以我的问题是:我做错了什么,我怎样才能得到加载页面的html?

非常感谢您!

PS:这是错误:

Exception in thread "JavaFX Application Thread" io.webfolder.ui4j.api.util.Ui4jException: java.lang.NullPointerException
    at io.webfolder.ui4j.webkit.aspect.WebKitAspect$CallableExecutor.run(WebKitAspect.java:41)
    at com.sun.javafx.application.PlatformImpl.lambda$null2(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater3(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run$$$capture(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java)
    at com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
    at com.sun.glass.ui.gtk.GtkApplication.lambda$null(GtkApplication.java:139)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.NullPointerException
    at io.webfolder.ui4j.webkit.dom.WebKitDocument.getBody_aroundBody12(WebKitDocument.java:74)
    at io.webfolder.ui4j.webkit.dom.WebKitDocument$AjcClosure13.run(WebKitDocument.java:1)
    at io.webfolder.ui4j.internal.aspectj.runtime.reflect.JoinPointImpl.proceed(JoinPointImpl.java:149)
    at io.webfolder.ui4j.webkit.aspect.WebKitAspect$CallableExecutor.run(WebKitAspect.java:39)
    ... 8 more

您使用 WebKit 是否有特定原因?这可以在标准 Java.

中相当容易地完成
URL oracle = new URL("http://www.oracle.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));

String inputLine;
while ((inputLine = in.readLine()) != null)
    System.out.println(inputLine);
    in.close();
}

以上直接摘自Oracle documentation