使用URL获取标题,元描述内容

时间:2012-03-31 18:16:12

标签: java url jsoup

我正在尝试从网址中提取标题和元标记的描述内容,这就是我所拥有的:

fin[] //urls in a string array

for (int f = 0; f < fin.length; f++)
{
Document finaldoc = Jsoup.connect(fin[f]).get(); //fin[f] contains url at each instance
Elements finallink1 = finaldoc.select("title");
out.println(finallink1);
Elements finallink2 = finaldoc.select("meta");
out.println(finallink2.attr("name"));
out.println(fin[f]); //printing url at last
}

但它不打印标题,只是将描述打印为“描述”并打印网址。

结果:

description plus.google.com generator en.wikipedia.org/wiki/google description earth.google.com

1 个答案:

答案 0 :(得分:19)

您可以使用:

String getMetaTag(Document document, String attr) {
    Elements elements = document.select("meta[name=" + attr + "]");
    for (Element element : elements) {
        final String s = element.attr("content");
        if (s != null) return s;
    }
    elements = document.select("meta[property=" + attr + "]");
    for (Element element : elements) {
        final String s = element.attr("content");
        if (s != null) return s;
    }
    return null;
}

然后:

 String title = document.title();
 String description = getMetaTag(document, "description");
 if (description == null) {
    description = getMetaTag(document, "og:description");
 }
 // and others you need to
 String ogImage = getMetaTag(document, "og:image") 

...