我正在编写基于Javafx的Web浏览器。我想获取当前在WebEngine中打开的 TITLE 网页。 谢谢你:)
答案 0 :(得分:3)
更好更好的方法就是使用WebEngine.getTitle()
以下是如何使用它的示例:
stage.titleProperty().bind(webView.getEngine().titleProperty());
答案 1 :(得分:1)
加载文档后,您可以使用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 ;
}
答案 2 :(得分:0)
只是一个不同的@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();
}