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

4

我正在尝试从URL中提取标题和meta标签的描述内容,这是我的代码:

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”打印出来,并打印URL。
结果: 描述 plus.google.com 生成器 en.wikipedia.org/wiki/google 描述 earth.google.com
1个回答

20

您可以使用这个:

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") 

....


7
值得指出的是,标题不是元标签,可以通过document.title()在jsoup中访问。 - Moshe Shaham
谢谢。已更新答案。 - Eugene Retunsky
此外,如果找不到“description”,您可以使用“og:description”调用您的方法:getMetaTag(document, "og:description"); - cnmuc
谢谢。由于Java中有很多“Element”,因此以下是相关的导入:import org.jsoup.select.Elements; - Siddhartha

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接