WebMagic 入门

这是接着上一章 WebMagic 简介,我们来搭建第一个 WebMagic 爬虫项目。

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

使用 Maven 创建 WebMagic 爬虫项目

我们先使用 Eclipse 创建一个 maven 项目。然后在pom.xml 中配置 WebMagic 的依赖。配置信息如下:

<dependency>
    <groupId>us.codecraft</groupId>
    <artifactId>webmagic-core</artifactId>
    <version>0.6.1</version>
</dependency>
<dependency>
    <groupId>us.codecraft</groupId>
    <artifactId>webmagic-extension</artifactId>
    <version>0.6.1</version>
</dependency>

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

<dependency>
    <groupId>us.codecraft</groupId>
    <artifactId>webmagic-extension</artifactId>
    <version>0.6.1</version>
    <exclusions>
        <exclusion>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
        </exclusion>
    </exclusions>
</dependency>

不使用maven的用户,可以去http://webmagic.io中下载最新的jar包。我将所有依赖的jar都打包在了一起,点这里下载。

WebMagic 爬虫项目

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

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
//:www.xttblog.com
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方法,选择“运行”,你会发现爬虫已经可以正常工作了!运行效果如下:

WebMagic demo 运行效果

WebMagic 入门

: » WebMagic 入门

原创文章,作者:wdmbts,如若转载,请注明出处:https://blog.ytso.com/tech/java/251568.html

(0)
上一篇 2022年5月3日 05:43
下一篇 2022年5月3日 05:47

相关推荐

发表回复

登录后才能评论