how to take title text from any web page in java

﹥>﹥吖頭↗ 提交于 2019-12-06 08:32:47

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.

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(); 

Or:

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

You can fetch the title of an HTML page easily using an XPath:

/html/head/title/text()

You can achieve this easily with Dom4J, and I think in JTidy as well.

Wee can't tell unless you post the code you are actually tyring to use to get the title, but this clearly won't work:

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

because the title element doesn't have a src attribute.

Try this,

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();
        }
    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!