推荐几个优秀的java爬虫项目

时间:2021-06-03 10:32:50
java爬虫项目
大型的:

适合做搜索引擎,分布式爬虫是其中一个功能。

比较成熟的爬虫。

小型的:

目标是在让你在5分钟之内写好一个爬虫。参考了crawler4j,如果经常需要写爬虫,需要写很多爬虫,还是不错的,因为上手肯定不止5分钟。缺点是它的定制性不强。

垂直、全栈式、模块化爬虫。更加适合抓取特定领域的信息。它包含了下载、调度、持久化、处理页面等模块。每一个模块你都可以自己去实现,也可以选择它已经帮你实现好的方案。这就有了很强的定制性。
看看它的例子:

编写第一个爬虫

 import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor; public class GithubRepoPageProcessor implements PageProcessor { private Site site = Site.me().setRetryTimes(3).setSleepTime(100); @Override
public void process(Page page) {
page.addTargetRequests(page.getHtml().links().regex("(https://github\\.com/\\w+/\\w+)").all());
page.putField("author", page.getUrl().regex("https://github\\.com/(\\w+)/.*").toString());
page.putField("name", page.getHtml().xpath("//h1[@class='entry-title public']/strong/a/text()").toString());
if (page.getResultItems().get("name")==null){
//skip this page
page.setSkip(true);
}
page.putField("readme", page.getHtml().xpath("//div[@id='readme']/tidyText()"));
} @Override
public Site getSite() {
return site;
} public static void main(String[] args) {
Spider.create(new GithubRepoPageProcessor()).addUrl("https://github.com/code4craft").thread(5).run();
}
}

使用注解编写爬虫

 @TargetUrl("https://github.com/\\w+/\\w+")
@HelpUrl("https://github.com/\\w+")
public class GithubRepo { @ExtractBy(value = "//h1[@class='entry-title public']/strong/a/text()", notNull = true)
private String name; @ExtractByUrl("https://github\\.com/(\\w+)/.*")
private String author; @ExtractBy("//div[@id='readme']/tidyText()")
private String readme; public static void main(String[] args) {
OOSpider.create(Site.me().setSleepTime(1000)
, new ConsolePageModelPipeline(), GithubRepo.class)
.addUrl("https://github.com/code4craft").thread(5).run();
}
}

两种方式,都可以实现对github项目的抓取。

原创:偉少