我需要动态获取URL的标题和描述。为此,我需要使用什么?

以以下URL为例:http://en.wikipedia.org/wiki/Stack_overflow

我需要提取URL的磁贴及其描述。您会喜欢下面的jsoup提取吗?

url.select("title");


如果是,如何提取URL描述?

最佳答案

我认为您需要像Jericho这样的HTML解析器。

看一下这个例子:
http://jericho.htmlparser.net/samples/console/src/ExtractText.java

特别是这两种方法:

private static String getTitle(Source source) {
    Element titleElement=source.getFirstElement(HTMLElementName.TITLE);
    if (titleElement==null) return null;
    // TITLE element never contains other tags so just decode it collapsing whitespace:
    return CharacterReference.decodeCollapseWhiteSpace(titleElement.getContent());
}

private static String getMetaValue(Source source, String key) {
    for (int pos=0; pos<source.length();) {
        StartTag startTag=source.getNextStartTag(pos,"name",key,false);
        if (startTag==null) return null;
        if (startTag.getName()==HTMLElementName.META)
            return startTag.getAttributeValue("content"); // Attribute values are automatically decoded
        pos=startTag.getEnd();
    }
    return null;
}

07-26 06:00