2. 快速開始
WebMagic主要包含兩個jar包:
webmagic-core-{version}.jar
和
webmagic-extension-{version}.jar
。在項目中添加這兩個包的依賴,即可使用WebMagic。
WebMagic預設使用Maven管理依賴,但是你也可以不依賴Maven進行使用。
2.1 使用Maven
WebMagic基于Maven進行建構,推薦使用Maven來安裝WebMagic。在你自己的項目(已有項目或者建立一個)中添加以下坐标即可:
<dependency>
<groupId>us.codecraft</groupId>
<artifactId>webmagic-core</artifactId>
<version>0.7.3</version>
</dependency>
<dependency>
<groupId>us.codecraft</groupId>
<artifactId>webmagic-extension</artifactId>
<version>0.7.3</version>
</dependency>
WebMagic使用slf4j-log4j12作為slf4j的實作.如果你自己定制了slf4j的實作,請在項目中去掉此依賴。
<dependency>
<groupId>us.codecraft</groupId>
<artifactId>webmagic-extension</artifactId>
<version>0.7.3</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
2.2 不使用Maven
不使用maven的使用者,可以去http://webmagic.io中下載下傳最新的jar包。我将所有依賴的jar都打包在了一起,點這裡下載下傳。
下載下傳之後進行解壓,然後在項目中import即可。
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnLxkTNwkTMfV1YUV0X4QDOyATMvw1cldWYtl2Yz92Lc12bj5ibkVXaulWcuMWanFWbiV2dvw1LcpDc0RHaiojIsJye.png)
因為WebMagic提倡自己定制,是以項目的源碼還是有必要看的。在http://webmagic.io上,你可以下載下傳最新的
webmagic-core-{version}-sources.jar
和
webmagic-extension-{version}-sources.jar
,點選"Attach Source"即可。
2.3 第一個爬蟲項目
在你的項目中添加了WebMagic的依賴之後,即可開始第一個爬蟲的開發了!我們這裡拿一個抓取Github資訊的例子:
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().setSleepTime();
@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().run();
}
}
點選main方法,選擇“運作”,你會發現爬蟲已經可以正常工作了!