【问题标题】:Web Crawler using jsoup使用 jsoup 的网络爬虫
【发布时间】:2016-04-21 19:48:49
【问题描述】:

我正在开发一个网络爬虫,但我卡住了,因为我无法获取所有可访问的链接,这是我的代码:

public class SNCrawler extends Thread {

    Specific s;

    HashSet<String> hs = new HashSet<String>();
    public SNCrawler(Specific s)
    {
        this.s = s;
    }

    public void crawl(String url) throws IOException {

        Document doc = Jsoup.connect(url).get();
        Elements links = doc.select("a");

        for (Element link : links)
        {
            if(isSuitable(link.attr("href")) && !hs.contains(link.attr("abs:href")))
            {
                hs.add(link.attr("href"));
                crawl(link.attr("href"));

            }
        }

    }

    public boolean isSuitable(String site)
    {
        boolean myBool = false;
        if(site.startsWith("http://www.svensktnaringsliv.se/") && !SNFilter.matcher(site).matches())
            if(site.contains(".pdf")) {
                hs.add(site);
                myBool=true;
            }else{
                hs.add(site);
                myBool=true;
            }
        return myBool;

    }

    private static final Pattern SNFilter = Pattern.compile(".*((/staff/|medarbetare|play|/member_organizations/|/sme_committee/|rm=print|/contact/|/brussels-office/|/about-us|/newsletter/|/advantagesweden/|service=print|#)).*");

    @Override
    public void run()
    {
        try {
            crawl("http://www.svensktnaringsliv.se/english/");
            for(String myS : hs)
            {
                System.out.println(myS);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

当程序到达网站的this 部分时,它不会从那里获得任何链接,this 页面也是如此,从那里我只得到 2 或 3 个链接,我已经查看了很多代码小时,但无法真正弄清楚为什么我被卡住了

【问题讨论】:

  • 我之前没有使用过jsoup,所以恐怕不能真正给你答案,但想知道为什么你不只使用像regex和phps这样的东西preg_match_all函数。 /&lt;a\s(.*)?href=["||']([a-zA-Z0-9\-\/\:\.\#\?\&amp;\%\=]+)["||']/ 应该获取文档中的所有链接。如果服务器允许,您可以使用curl 甚至只是file_get_contents,请帮助here
  • 对不起,这是一个更准确的模式(或者我发现了)/&lt;a\s[^&gt;]*href=[\"||\']([^\"\']*)[\"||\'][^&gt;]*&gt;/ixgU

标签: java html css jsoup


【解决方案1】:

当程序到达网站的这一部分时,它不会从那里获得任何链接

抓取功能应使用绝对网址。 请尝试以下功能:

public void crawl(String url) throws IOException {
    Document doc = Jsoup.connect(url).get();
    Elements links = doc.select("a");

    for (Element link : links) {
        String foundUrl = link.attr("abs:href").toLowerCase();

        if( isSuitable(foundUrl) && ( !hs.contains(foundUrl) ) ) {
            hs.add(foundUrl);
            crawl(foundUrl);
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多