如何获取所有链接(<a href="">) in URL</a>

时间:2014-02-21 13:29:52

标签: java

我得到一些网址,我需要搜索此网址中的所有链接,然后只显示它们,就是这些。

我在java中写道:

        PrintWriter writer=new PrintWriter("Web.txt");

        URL oracle = new URL("http://edition.cnn.com/");
        BufferedReader in = new BufferedReader(
        new InputStreamReader(oracle.openStream()));

        String inputLine;
        while ((inputLine = in.readLine()) != null)
        {

            writer.println(inputLine);
            System.out.println(inputLine);
        }
        in.close();

现在我的问题是如何在这个巨大的文件中只找到链接?

我想过<a href" ... ... ..>,但它并不总是正确的。

由于

1 个答案:

答案 0 :(得分:1)

JSOUP是要走的路!它是一个Java API,您可以在其上解析 HTML 文档(本地或外部文档),并使用jQuery类似语法在 DOM 结构上导航。

获取所有链接的代码应如下所示:

Document doc = Jsoup.connect("http://edition.cnn.com").get(); // Parse this URL's HTML
Elements elements = doc.select("a"); // Search for all <a> elements

然后,列出每个链接并将其保存到您的文件中:

for (Element element : elements) {
    writer.println(element.attr("href")); // Get the "href" attribute from the element
}
相关问题