【问题标题】:Find the TITLE of current webpage open in WebEngine [[JAVAFX]]查找WebEngine中打开的当前网页的TITLE [[JAVAFX]]
【发布时间】:2015-03-05 10:14:12
【问题描述】:

我正在编写一个基于 Javafx 的 Web 浏览器。我想获取当前在 WebEngine 中打开的网页的 TITLE。 谢谢你:)

【问题讨论】:

    标签: javafx javafx-8 javafx-webengine


    【解决方案1】:

    更好更好的方法是使用WebEngine.getTitle()

    这是一个如何使用它的示例:

    stage.titleProperty().bind(webView.getEngine().titleProperty());
    

    【讨论】:

    • 我不知道为什么,在很多网站中,当网站明确有标题时,我会获得null
    • @pupeno 这可能是因为您在标题可用之前访问了它。您应该为该属性注册一个侦听器。或者更好地像我的示例绑定到它。
    【解决方案2】:

    加载文档后,您可以使用 DOM API 查找标题。 (我通常不喜欢 DOM API,但您可以这样做。)

    private String getTitle(WebEngine webEngine) {
        Document doc = webEngine.getDocument();
        NodeList heads = doc.getElementsByTagName("head");
        String titleText = webEngine.getLocation() ; // use location if page does not define a title
        if (heads.getLength() > 0) {
            Element head = (Element)heads.item(0);
            NodeList titles = head.getElementsByTagName("title");
            if (titles.getLength() > 0) {
                Node title = titles.item(0);
                titleText = title.getTextContent();
            }
        }
        return titleText ;
    }
    

    【讨论】:

    • 我是 JAVAfx 的新手,在执行此操作时遇到错误 error: incompatible types: org.w3c.dom.Document cannot be converted to sun.plugin.dom.core.Documenterror: incompatible types: org.w3c.dom.Node cannot be converted to sun.plugin.dom.core.Node @James_D
    • 您的导入有误。确保为正在调用的方法的返回类型导入正确的类(即,您需要 org.w3c.dom 导入,而不是私有的 sun.plugin 类)。
    • 我找不到任何 org.w3c.dom 导入 Node title = titles.item(0); 和 `Document doc = webEngine.getDocument();如果你能提供我确切的进口,将不胜感激
    • 根据错误信息,您的代码中必须有import sun.plugin.dom.core.Document;。应该是import org.w3c.dom.Document;Node 也是如此。
    • 我已经导入了 import org.w3c.dom.Document;import org.w3c.dom.Node; 但是为什么 Netbeans 找不到这个导入,它给出了一个提示 cannot find symbol
    【解决方案3】:

    只是@James_D 出色答案的不同实现(少一点冗长,多一点 Java 8 风格):

    private String getTitle(WebEngine webEngine) {
        Document doc = webEngine.getDocument();
        NodeList heads = doc.getElementsByTagName("head");
        String titleText = webEngine.getLocation(); // use location if page does not define a title
        return getFirstElement(heads)
                .map(h -> h.getElementsByTagName("title"))
                .flatMap(this::getFirstElement)
                .map(Node::getTextContent).orElse(titleText);
    }
    
    private Optional<Element> getFirstElement(NodeList nodeList) {
        if (nodeList.getLength() > 0 && nodeList.item(0) instanceof Element) {
            return Optional.of((Element) nodeList.item(0));
        }
        return Optional.empty();
    }
    

    【讨论】:

      猜你喜欢
      • 2021-07-07
      • 1970-01-01
      • 2013-07-07
      • 1970-01-01
      • 2011-12-09
      • 1970-01-01
      • 2010-11-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多