WebMagic基础与Maven管理依赖
2024-09-05 02:21:50
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>
在你的项目中添加了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(3).setSleepTime(100);
- @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(5).run();
- }
- }
点击main方法,选择“运行”,你会发现爬虫已经可以正常工作了!
最新文章
- ASP.NET Core 运行原理剖析1:初始化WebApp模版并运行
- 推荐15款最好的 Twitter Bootstrap 开发工具
- nodejs学习篇 (1)webstorm创建nodejs + express + jade 的web 项目
- Theano2.1.12-基础知识之使用GPU
- iOS 在UILabel显示不同的字体和颜色(转)
- JMeter学习-006-Could not open/create prefs root node Software\JavaSoft\Prefs at root 0x80000002 解决办法(windows 7)
- css中transition的使用以及:before:after的使用(小样式)
- javascript 返回数组中不重复的元素
- Java基础-事件处理
- CSS width:100%和width:auto的区别
- Android:创建Android工程
- Tar打包、压缩与解压缩到指定目录的方法
- automake/autoconf的简单例子
- 1.WF 4.5在项目中直接使用的问题
- 网络编程一定要看过的socket大山
- Manjaro使用笔记-使用中国源的方法
- ASP.Net Core 2.2 MVC入门到基本使用系列 (四)(转)
- Makefile依赖关系中的竖线“|”
- input file 文件上传标签的样式美化
- Applese走迷宫-bfs