【问题标题】:Web Crawler specifically for downloading images and files专门用于下载图像和文件的网络爬虫
【发布时间】:2013-01-31 10:21:29
【问题描述】:

我正在为我的一门课做作业。

我应该编写一个网络爬虫,从给定指定爬网深度的网站下载文件和图像。

我被允许使用第三方解析 api,所以我使用 Jsoup。我也试过 htmlparser。两个不错的软件,但它们并不完美。

我在处理 url 之前使用 default java URLConnection 来检查内容类型,但随着链接数量的增加,它变得非常慢。

问题:有人知道任何专门的图像和链接解析器 API 吗?

我可以开始使用 Jsoup 编写我的,但我很懒。此外,如果有可行的解决方案,为什么还要重新发明轮子?任何帮助将不胜感激。

我需要在循环遍历链接时检查 contentType 以检查链接是否指向文件,以一种有效的方式,但 Jsoup 没有我需要的内容。这是我所拥有的: **

    HttpConnection mimeConn =null;
    Response mimeResponse = null;
    for(Element link: links){

        String linkurl =link.absUrl("href");
        if(!linkurl.contains("#")){

            if(DownloadRepository.curlExists(link.absUrl("href"))){
                continue;
            }

            mimeConn = (HttpConnection) Jsoup.connect(linkurl);
            mimeConn.ignoreContentType(true);
            mimeConn.ignoreHttpErrors(true);
            mimeResponse =(Response) mimeConn.execute();

            WebUrl webUrl = new WebUrl(linkurl,currentDepth+1);
            String contentType = mimeResponse.contentType();

            if(contentType.contains("html")){
                page.addToCrawledPages(new WebPage(webUrl));
            }else if(contentType.contains("image")){                    
                page.addToImages(new WebImage(webUrl));
            }else{
                page.addToFiles(new WebFile(webUrl));
            }

            DownloadRepository.addCrawledURL(linkurl);

        }**

更新 根据 Yoshi 的回答,我能够让我的代码正常工作。这是链接:

https://github.com/unekwu/cs_nemesis/blob/master/crawler/crawler/src/cu/cs/cpsc215/project1/parser/Parser.java

【问题讨论】:

  • 如果你懒惰检查wget 做同样的事情
  • Java 开发涉及大量研究,为给定的问题领域寻找最佳 API 并使用它来解决您的问题。当然,要偷懒,不要重新发明轮子,但不要懒到不做自己的研究。

标签: java html-parsing jsoup web-crawler


【解决方案1】:

使用jSoup 我认为这个API 足以满足您的目的。你也可以在这个网站上找到好的食谱。

几个步骤:

  1. Jsoup: how to get an image's absolute url?
  2. how to download image from any web page in java
  3. 您可以编写自己的递归方法,遍历包含必要域名或相关链接的页面上的链接。使用这种方式抓取所有链接并找到其上的所有图像。自己写是不错的做法。

你不需要使用 URLConnection 类,jSoup 有它的包装器。

例如

只需一行代码即可获取 DOM 对象:

Document doc = Jsoup.connect("http://en.wikipedia.org/").get();

代替这段代码:

    URL oracle = new URL("http://www.oracle.com/");
    URLConnection yc = oracle.openConnection();
    BufferedReader in = new BufferedReader(new InputStreamReader(
                                yc.getInputStream()));
    String inputLine;
    while ((inputLine = in.readLine()) != null) 
        System.out.println(inputLine);
    in.close();

更新1 尝试在您的代码中添加下一行:

Connection.Response res = Jsoup.connect("http://en.wikipedia.org/").execute();
String pageContentType = res.contentType();

【讨论】:

  • 我需要有效地检查 contentType 但 Jsoup 没有我需要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多