如何从java中的任何网页获取标题文本 [英] how to take title text from any web page in java
问题描述
我正在使用java从网页上获取标题文本。
I am using java to fetch the title text from web page.
我使用标记名称从网页中获取图像,如下所示:
I have fetched image from web page using Tag name as follows:
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<String> list=new ArrayList<String>();
list.add(img.item(i).getAttributes().getNamedItem("src").getNodeValue());
它有效,但我想从网页(www.yahoo.com)获取标题标签使用相同的代码
如上所述。我提到了getElementsByTagName(title);但它不起作用。
请帮助我,如何使用如上所述的jtidy解析器。
It is working,But I want to fetch title tag from web page(www.yahoo.com) using same code as above.I have mentioned getElementsByTagName("title"); but it is not working. Please help me,how to do that using jtidy parser as above.
推荐答案
观察NodeList索引从0(我看到你的int i = 1;) http://download.oracle.com/javase/1.4.2/docs/api/org/w3c/dom/NodeList.html 。
Watch that the NodeList index starts at 0 (i see your "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标签有子元素。所以:
Also, you can "getNodeValue()" of an Attribute (ie "src"), but not of an Element http://download.oracle.com/javase/1.5.0/docs/api/org/w3c/dom/Node.html. In this case you can use "getTextContent()", because I dont believe the "title" tag has child Elements. So:
String titleText = doc.getElementsByTagName("title").item(0).getTextContent();
或者:
String titleText = doc.getElementsByTagName("title").item(0).getFirstChild().getNodeValue();
这篇关于如何从java中的任何网页获取标题文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!