如何在访问网页之前获取网页内容

3
如何获取给定URL的网页描述/内容。 (类似于Google为每个结果链接提供简短的描述)。 我想在我的jsp页面中实现此功能。
提前感谢!
1个回答

4

想法: 以流的形式打开URL,然后解析其描述元标记中的字符串。

抓取URL内容:

URL url = new URL("http://www.url-to-be-parsed.com/page.html");
    BufferedReader in = new BufferedReader(
                new InputStreamReader(
                url.openStream()));

根据你所使用的HTML解析库(流、字符串等),需要微调上面的代码。

对标签进行HTML解析:

<meta name="description" content="This is a place where webmasters can put a description about this web page" />

您可能也对获取该页面的标题感兴趣:
<title>This is the title of the page!</title>

注意:正则表达式在HTML文档上似乎不可靠,因此最好使用HTML解析器

使用HTML解析器的示例:

  1. 使用HasAttributeFilter按具有name="description"属性的标记进行过滤
  2. 尝试将Node转换为MetaTag
  3. 使用MetaTag.getAttribute()获取content

代码:

import org.htmlparser.Node;
import org.htmlparser.Parser;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.tags.MetaTag;

public class HTMLParserTest {
    public static void main(String... args) {
        Parser parser = new Parser();
        //<meta name="description" content="Some texte about the site." />
        HasAttributeFilter filter = new HasAttributeFilter("name", "description");
        try {
            parser.setResource("http://www.youtube.com");
            NodeList list = parser.parse(filter);
            Node node = list.elementAt(0);

            if (node instanceof MetaTag) {
                MetaTag meta = (MetaTag) node;
                String description = meta.getAttribute("content");

                System.out.println(description);
                // Prints: "YouTube is a place to discover, watch, upload and share videos."
            }

        } catch (ParserException e) {
            e.printStackTrace();
        }
    }

}

注意事项:

如果每次加载页面时都在JSP中执行此操作,由于与URL的网络I/O可能会导致减速。更糟糕的是,如果您对包含许多URL链接的页面进行每次实时操作,则由于n个URL的顺序操作,减速可能会非常严重。也许您可以将此信息存储在数据库中,并根据需要刷新它们,而不是在JSP中实时执行。


非常感谢您的回复。我想提取元标记的内容信息。我正在使用HTML解析器(http://htmlparser.sourceforge.net/samples.html)。请问您能帮忙吗? - smartcode
好了,我终于花了一些时间熟悉他们的API。看起来现在运行得很好。因为我也会使用它,如果我发现更有效的方法,我会进行更新。 - bakkal
还有一个问题,兄弟。根据你的回答,是否也可以获取标题的值?我已经根据你的回答尝试过了,但仍然无法得到结果!有什么想法吗?提前感谢! - smartcode

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