2. 快速开始

WebMagic主要包含两个jar包:webmagic-core-{version}.jarwebmagic-extension-{version}.jar。在项目中添加这两个包的依赖,即可使用WebMagic。

WebMagic默认使用Maven管理依赖,但是你也可以不依赖Maven进行使用。

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

 

 

2.1 使用Maven

WebMagic基于Maven进行构建,推荐使用Maven来安装WebMagic。在你自己的项目(已有项目或者新建一个)中添加以下坐标即可:

  1.   <dependency>
  2.   <groupId>us.codecraft</groupId>
  3.   <artifactId>webmagic-core</artifactId>
  4.   <version>0.7.3</version>
  5.   </dependency>
  6.   <dependency>
  7.   <groupId>us.codecraft</groupId>
  8.   <artifactId>webmagic-extension</artifactId>
  9.   <version>0.7.3</version>
  10.   </dependency>

WebMagic使用slf4j-log4j12作为slf4j的实现.如果你自己定制了slf4j的实现,请在项目中去掉此依赖。

  1.   <dependency>
  2.   <groupId>us.codecraft</groupId>
  3.   <artifactId>webmagic-extension</artifactId>
  4.   <version>0.7.3</version>
  5.   <exclusions>
  6.   <exclusion>
  7.   <groupId>org.slf4j</groupId>
  8.   <artifactId>slf4j-log4j12</artifactId>
  9.   </exclusion>
  10.   </exclusions>
  11.   </dependency>  

    在你的项目中添加了WebMagic的依赖之后,即可开始第一个爬虫的开发了!我们这里拿一个抓取Github信息的例子:

    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.   }

    点击main方法,选择“运行”,你会发现爬虫已经可以正常工作了!

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄