如何从java中的任何网页获取标题文本
我正在使用java从网页上获取标题文本。
我使用Tag名称从网页中获取图像,如下所示:
int i=1; InputStream in=new URL("www.yahoo.com").openStream(); org.w3c.dom.Document doc= new Tidy().parseDOM(in, null); NodeList img=doc.getElementsByTagName("img"); ArrayList list=new ArrayList(); list.add(img.item(i).getAttributes().getNamedItem("src").getNodeValue());
它正在工作,但我想使用与上面相同的代码从网页(www.yahoo.com)获取标题标签。我已经提到了getElementsByTagName(“title”); 但它不起作用。 请帮助我,如何使用如上所述的jtidy解析器。
观察NodeList索引从0开始(我看到你的“int i = 1;”) http://download.oracle.com/javase/1.4.2/docs/api/org/w3c/dom/NodeList.html 。
此外,您可以使用属性(即“src”)的“getNodeValue()”,但不能使用元素http://download.oracle.com/javase/1.5.0/docs/api/org/w3c/dom/ Node.html 。 在这种情况下,你可以使用“getTextContent()”,因为我不相信“title”标签有子元素。 所以:
String titleText = doc.getElementsByTagName("title").item(0).getTextContent();
要么:
String titleText = doc.getElementsByTagName("title").item(0).getFirstChild().getNodeValue();
您可以使用XPath轻松获取HTML页面的标题:
/html/head/title/text()
你可以使用Dom4J轻松实现这一点,我也认为在JTidy中也是如此。
除非你发布实际上用来获得标题的代码,否则我们无法判断,但这显然不起作用:
list.add(img.item(i).getAttributes().getNamedItem("src").getNodeValue());
因为title
元素没有src
属性。