WebMagic文档:http://webmagic.io/docs/zh/index.html。
一:快速使用
–推荐使用maven项目管理工具
maven依赖清单:123456789101112131415161718192021<dependency><groupId>us.codecraft</groupId><artifactId>webmagic-core</artifactId><version>0.5.3</version></dependency><dependency><groupId>us.codecraft</groupId><artifactId>webmagic-extension</artifactId><version>0.5.3</version></dependency><dependency><groupId>us.codecraft</groupId><artifactId>webmagic-extension</artifactId><version>0.5.3</version><exclusions><exclusion><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId></exclusion></exclusions></dependency>‘HelloWorld’例
12345678910111213141516171819202122/**3. Created by lwc on 16/10/17.*/public class UniversalBookSpider implements PageProcessor {private Site site = Site.me().setRetryTimes(3).setSleepTime(100);//设置重复尝试次数3次,以及中间睡眠时间100毫秒。@Overridepublic void process(Page page) {String bookname = page.getHtml().css("div.title", "text").get();//获取ID为title的DIV的内容}@Overridepublic Site getSite() {return site;}public static void main(String args[]) {UniversalBookSpider universalMetaSpider = new UniversalBookSpider();//新建爬虫体Spider spider = Spider.create(universalMetaSpider);//新建爬虫类spider.addUrl("www.4399.com");//往爬虫队列中添加一个目标网址spider.thread(5).run();//设置5个线程共同工作。还有一种开始爬虫的方法:spider.thread(5).start();不同处在于:run()是block的,但是start是非阻塞的。}}
执行main方法就可以获得www.4399.com网站中id为·title·的DIV的内容。
二:相应的API拓展
- setExitWhenComplete(Boolean bool):
spider.setExitWhenComplete(Boolean bool);参数决定是否在完成爬虫任务之后退出爬虫。一般在重复利用爬虫执行体的情况下选择false。 - DOM选择器
在page.getHtml().css(“div.title”, “text”).get();的CSS()方法中的选择器与jQuery的选择与法一致(jQuery的选择器语法就不在这里赘述)
三:多级爬虫的信息传递
假设有A,B,C三个爬虫,A在处理完自己的界面之后想把详细info-A传给B,B处理完之后要把Info-A、info-B传给C。
代码示例:1234567public synchronized void setSpiderAndRun(String startUrl, int threadNum, boolean exitWhenFinish, TestBook testBook, BookRule testRule) {if (spider == null) {spider = Spider.create(new UniversalBookChapter(testBook, testRule)).addUrl(startUrl).thread(threadNum).setExitWhenComplete(exitWhenFinish);spider.run();} else {spider.addUrl(startUrl).setExitWhenComplete(exitWhenFinish);}
setSpiderAndRun()方法可以在上一级的爬虫中调用,只要A中new出了B的实例,便可以通过该方法来传递信息。