简单搭建webMagic爬虫步骤

1、简介

WebMagic是一个简单灵活的Java爬虫框架。基于WebMagic,你可以快速开发出一个高效、易维护的爬虫。

官网:http://webmagic.io/
中文官网:http://webmagic.io/docs/zh/

示例:



public class GithubRepoPageProcessor implements PageProcessor {

    private Site site = Site.me().setRetryTimes(3).setSleepTime(1000).setTimeOut(10000);

    @Override
    public void process(Page page) {
        page.addTargetRequests(page.getHtml().links().regex("(https://github\.com/[\w\-]+/[\w\-]+)").all());
        page.addTargetRequests(page.getHtml().links().regex("(https://github\.com/[\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();
    }
}


2、步骤

2.1 使用Maven添加依赖

2.1.1 爬虫依赖

<!--爬虫框架-->
<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>

2.1.2 日志依赖

<!--日志依赖-->
<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使用slf4j-log4j12作为slf4j的实现.如果你自己定制了slf4j的实现,请在项目中去掉此依赖。

2.2 不使用Maven

不使用maven的用户,可以去http://webmagic.io中下载最新的jar包。我将所有依赖的jar都打包在了一起,点这里下载。下载之后进行解压,然后在项目中import即可。
因为WebMagic提倡自己定制,所以项目的源码还是有必要看的。在http://webmagic.io上,你可以下载最新的webmagic-core-{version}-sources.jarwebmagic-extension-{version}-sources.jar,点击"Attach Source"即可。

2.3 爬虫脚本

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;

import java.util.ArrayList;
import java.util.List;

public class MyProcessor implements PageProcessor {
    // 抓取网站的相关配置,包括编码、抓取间隔、重试次数等
    private Site site = Site.me().setRetryTimes(5).setSleepTime(100);
    private static int count = 0; //记录爬取的次数

    @Override
    public Site getSite() {
        return site;
    }

    @Override
    public void process(Page page) {
        //判断链接是否符合 https://sr.aihuishou.com/image/5a28b40bc60057c40a000005.png?x-oss-process=image/resize,w_150/任意个数字字母.png格式
        if (!page.getUrl().regex("https://sr.aihuishou.com/image/[a-z 0-9 A-Z]{24}.png").match()) {
            List<String> phoneImg = page.getHtml().xpath("//div[@class="product-list-wrapper"]").xpath("//img/@src").all();
            List<String> urlList = page.getHtml().xpath("//div[@class="product-list-wrapper"]").xpath("//a/@href").all();
            List<String> endUrls = new ArrayList<>();
            String baseUrl = "https://www.aihuishou.com";
            for (String url : urlList) {
                endUrls.add(baseUrl + url);
            }

            System.out.println("手机图片:" + phoneImg);
            System.out.println("手机地址:" + endUrls);
            //如果当前页面包含下一页
            if (page.toString().contains("下一页")) {
                //获取下一页的链接
                String nextUrl = page.getHtml().xpath("//a[@class='next no_hover']/@href").toString();
                //加入满足条件的链接,让其发送子请求
                page.addTargetRequest(baseUrl + nextUrl);

            }
            count++;

        } else {
            //获取页面需要的内容
            System.out.println("抓取的内容:" +
                    page.getHtml().xpath("//div[@class="product-list-wrapper"]").get()
            );
        }
    }

    public static void main(String[] args) {
        long startTime, endTime;
        System.out.println("开始爬取...");
        startTime = System.currentTimeMillis();
        Spider.create(new MyProcessor()).addUrl("https://www.aihuishou.com/shouji?all=True").thread(10).run();
        endTime = System.currentTimeMillis();
        System.out.println("爬取结束,耗时约" + ((endTime - startTime) / 1000) + "秒,抓取了" + count + "条记录");
    }

}

运行结果(因为我是直接输出在控制台的,这里只展示一部分结果):
image.png
完成所需。

3、注意事项

3.1 页面元素的抽取

第二部分是爬虫的核心部分:对于下载到的Html页面,你如何从中抽取到你想要的信息?WebMagic里主要使用了三种抽取技术:XPath、正则表达式和CSS选择器。另外,对于JSON格式的内容,可使用JsonPath进行解析。

3.1.1 XPath

XPath本来是用于XML中获取元素的一种查询语言,但是用于Html也是比较方便的。例如:

page.getHtml().xpath("//h1[@class='entry-title public']/strong/a/text()")

这段代码使用了XPath,它的意思是“查找所有class属性为'entry-title public'的h1元素,并找到他的strong子节点的a子节点,并提取a节点的文本信息”。
对应的Html是这样子的:image.png

3.1.2 CSS选择器

CSS选择器是与XPath类似的语言。如果大家做过前端开发,肯定知道$('h1.entry-title')这种写法的含义。客观的说,它比XPath写起来要简单一些,但是如果写复杂一点的抽取规则,就相对要麻烦一点。

3.1.3 正则表达式

正则表达式则是一种通用的文本抽取语言。

page.addTargetRequests(page.getHtml().links().regex("(https://github\.com/\w+/\w+)").all());
  1. 这段代码就用到了正则表达式,它表示匹配所有"https://github.com/code4craft/webmagic"这样的链接。
  2. JsonPath
    JsonPath是于XPath很类似的一个语言,它用于从Json中快速定位一条内容。WebMagic中使用的JsonPath格式可以参考这里:https://code.google.com/p/json-path/

原文地址:https://www.cnblogs.com/tidetrace/p/10918155.html