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> </dep
endency>
例子: 測試可用的
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
public class MyProcessor implements PageProcessor {
// 抓取網站的相關配置,包括編碼、抓取間隔、重試次數等
private Site site = Site.me().setRetryTimes(3).setSleepTime(100);
private static int count =0;
@Override
public Site getSite() {
return site;
}
@Override
public void process(Page page) {
//判斷鏈接是否符合http://www.cnblogs.com/任意個數字字母-/p/7個數字.html格式
if(!page.getUrl().regex("http://www.cnblogs.com/[a-z 0-9 -]+/p/[0-9]{7}.html").match()){
//加入滿足條件的鏈接
page.addTargetRequests(
page.getHtml().xpath("//*[@id=\"post_list\"]/div/div[@class='post_item_body']/h3/a/@href").all());
//獲取頁面需要的內容
System.out.println("抓取的內容:"+
page.getHtml().xpath("//*[@id=\"Header1_HeaderTitle\"]/text()").get()
);
count ++;
}
}
public static void main(String[] args) {
long startTime, endTime;
System.out.println("開始爬取...");
startTime = System.currentTimeMillis();
Spider.create(new MyProcessor()).addUrl("https://www.cnblogs.com/").thread(5).run();
endTime = System.currentTimeMillis();
System.out.println("爬取結束,耗時約" + ((endTime - startTime) / 1000) + "秒,抓取了"+count+"條記錄");
}
}