首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用javafx从get视图中获取内容

使用javafx从get视图中获取内容
EN

Stack Overflow用户
提问于 2013-01-11 15:16:41
回答 2查看 29.3K关注 0票数 22

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

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

代码语言:javascript
复制
try
{
    String str=webview1.getEngine().getDocment().Body().outerHtml();
}
catch(Exception ex)
{
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-01-12 02:13:09

根据代码判断,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的原因:

代码语言:javascript
复制
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();
}
票数 23
EN

Stack Overflow用户

发布于 2013-12-30 01:29:12

代码语言:javascript
复制
String html = (String) webEngine.executeScript("document.documentElement.outerHTML");
票数 46
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14273450

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档