2

我正在使用 java 从网页中获取标题文本。

我使用标签名称从网页中获取图像,如下所示:

    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 解析器来做到这一点。

4

4 回答 4

2

注意 NodeList 索引从 0 开始(我看到你的“int i = 1;”)http://download.oracle.com/javase/1.4.2/docs/api/org/w3c/dom/NodeList.html

此外,您可以“getNodeValue()”的属性(即“src”),但不是元素http://download.oracle.com/javase/1.5.0/docs/api/org/w3c/dom/节点.html。在这种情况下,您可以使用“getTextContent()”,因为我不相信“title”标签有子元素。所以:

String titleText = doc.getElementsByTagName("title").item(0).getTextContent(); 

或者:

String titleText = doc.getElementsByTagName("title").item(0).getFirstChild().getNodeValue(); 
于 2011-05-07T10:44:58.760 回答
1

您可以使用 XPath 轻松获取 HTML 页面的标题:

/html/head/title/text()

您可以使用Dom4J轻松实现这一点,我认为在 JTidy 中也是如此。

于 2011-05-07T08:07:29.633 回答
0

除非您发布实际用于获取标题的代码,否则 Wee 无法判断,但这显然行不通:

    list.add(img.item(i).getAttributes().getNamedItem("src").getNodeValue());

因为该title元素没有src属性。

于 2011-05-07T06:39:43.330 回答
0

尝试这个,

InputStream response = null;
    try {
        String url = "http://example.com/"; // specify the URL
        response = new URL(url).openStream();


        Scanner scanner = new Scanner(response);
        String responseBody = scanner.useDelimiter("\\A").next();
        System.out.println(responseBody.substring(responseBody.indexOf("<title>") + 7, responseBody.indexOf("</title>"))); // it fetches the text inside the title tag

    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        try {
            response.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
于 2019-04-30T03:40:11.940 回答