java爬虫抓取动态网页(让你在5分钟之内写好一个爬虫)

优采云 发布时间: 2021-10-07 23:08

  java爬虫抓取动态网页(让你在5分钟之内写好一个爬虫)

  小型的:

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

  垂直、全栈、模块化爬虫。它更适合捕捉特定领域的信息。收录下载、调度、持久化、页面处理等模块。您可以自己实现每个模块,也可以选择它已经为您实现的解决方案。这使得它高度可定制。

  看看它的例子:

  编写第一个爬虫

   1 import us.codecraft.webmagic.Page;

2 import us.codecraft.webmagic.Site;

3 import us.codecraft.webmagic.Spider;

4 import us.codecraft.webmagic.processor.PageProcessor;

5

6 public class GithubRepoPageProcessor implements PageProcessor {

7

8 private Site site = Site.me().setRetryTimes(3).setSleepTime(100);

9

10 @Override

11 public void process(Page page) {

12 page.addTargetRequests(page.getHtml().links().regex("(https://github\\.com/\\w+/\\w+)").all());

13 page.putField("author", page.getUrl().regex("https://github\\.com/(\\w+)/.*").toString());

14 page.putField("name", page.getHtml().xpath("//h1[@class=\'entry-title public\']/strong/a/text()").toString());

15 if (page.getResultItems().get("name")==null){

16 //skip this page

17 page.setSkip(true);

18 }

19 page.putField("readme", page.getHtml().xpath("//div[@id=\'readme\']/tidyText()"));

20 }

21

22 @Override

23 public Site getSite() {

24 return site;

25 }

26

27 public static void main(String[] args) {

28 Spider.create(new GithubRepoPageProcessor()).addUrl("https://github.com/code4craft").thread(5).run();

29 }

30 }

  使用注解编写爬虫

   1 @TargetUrl("https://github.com/\\w+/\\w+")

2 @HelpUrl("https://github.com/\\w+")

3 public class GithubRepo {

4

5 @ExtractBy(value = "//h1[@class=\'entry-title public\']/strong/a/text()", notNull = true)

6 private String name;

7

8 @ExtractByUrl("https://github\\.com/(\\w+)/.*")

9 private String author;

10

11 @ExtractBy("//div[@id=\'readme\']/tidyText()")

12 private String readme;

13

14 public static void main(String[] args) {

15 OOSpider.create(Site.me().setSleepTime(1000)

16 , new ConsolePageModelPipeline(), GithubRepo.class)

17 .addUrl("https://github.com/code4craft").thread(5).run();

18 }

19 }

  无论哪种方式,都可以抓取github项目。

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线