【问题标题】:get the contents from the webview using javafx使用 javafx 从 webview 获取内容
【发布时间】:2012-12-25 18:10:03
【问题描述】:

我正在使用 JAVA FX 控件开发一个摇摆应用程序。在我的应用程序中,我必须打印出 webview 中显示的 html 页面。我正在尝试的是在 HtmlDocuement 的帮助下将 webview 的 html 内容加载到字符串中。

要从 web 视图加载 html 文件的内容,我正在使用以下代码,但它不起作用:

try
{
    String str=webview1.getEngine().getDocment().Body().outerHtml();
}
catch(Exception ex)
{
}

【问题讨论】:

    标签: java webview javafx-2 javafx


    【解决方案1】:
    String html = (String) webEngine.executeScript("document.documentElement.outerHTML");
    

    【讨论】:

    • 如果没有工人,这一个班轮将无法工作。将返回空 html。它也不适用于像 google.com 这样的网站。不会返回实时 DOM,只返回底层 html/javascript。
    【解决方案2】:

    WebEngine.getDocument 返回org.w3c.dom.Document,而不是您期望通过代码判断的 JavaScript 文档。

    不幸的是,打印出org.w3c.dom.Document 需要大量的编码。您可以尝试What is the shortest way to pretty print a org.w3c.dom.Document to stdout? 的解决方案,请参见下面的代码。

    请注意,您需要等到文档加载完毕才能使用Document。这就是这里使用LoadWorker 的原因:

    public void start(Stage primaryStage) {
        WebView webview = new WebView();
        final WebEngine webengine = webview.getEngine();
        webengine.getLoadWorker().stateProperty().addListener(
                new ChangeListener<State>() {
                    public void changed(ObservableValue ov, State oldState, State newState) {
                        if (newState == Worker.State.SUCCEEDED) {
                            Document doc = webengine.getDocument();
                            try {
                                Transformer transformer = TransformerFactory.newInstance().newTransformer();
                                transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
                                transformer.setOutputProperty(OutputKeys.METHOD, "xml");
                                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                                transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
                                transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    
                                transformer.transform(new DOMSource(doc),
                                        new StreamResult(new OutputStreamWriter(System.out, "UTF-8")));
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        }
                    }
                });
        webengine.load("http://stackoverflow.com");
        primaryStage.setScene(new Scene(webview, 800, 800));
        primaryStage.show();
    }
    

    【讨论】:

    • 如果网站有错误 html ex,您的方法将检索丢失的内容:我非常关心这个主题如果您有修复请帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-03
    • 2011-01-23
    • 2012-01-02
    • 2020-05-09
    • 1970-01-01
    • 2014-05-09
    • 1970-01-01
    相关资源
    最近更新 更多