欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

webmagic小试牛刀

程序员文章站 2024-02-23 08:02:04
...

webmagic是java里头比较优秀的一个爬虫框架:

  • 使用Jsoup作为HTML解析工具,并基于其开发了解析XPath的工具Xsoup。
  • 默认使用了Apache HttpClient作为下载工具。

这里展示一下入门级使用。

maven

        <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>

启动类

public static void main(String[] args) {
    Spider.create(new GithubRepoPageProcessor())
            //从https://github.com/code4craft开始抓    
            .addUrl("https://github.com/code4craft")
            //设置Scheduler,使用Redis来管理URL队列
            .setScheduler(new RedisScheduler("localhost"))
            //设置Pipeline,将结果以json方式保存到文件
            .addPipeline(new JsonFilePipeline("D:\\data\\webmagic"))
            //开启5个线程同时执行
            .thread(5)
            //启动爬虫
            .run();
}

PageProcessor

核心的工作主要是自定义PageProcessor,比如

new PageProcessor() {

            @Override
            public void process(Page page) {
                List<String> links = page.getHtml()
                        .xpath("//table[@id='jrjthreadtable']//td/a/@href")
                        .regex("/msg,\\d+.*.html")
                        .all();
                System.out.println(links);
            }

            @Override
            public Site getSite() {
                return Site.me()
                        .setRetryTimes(3)
                        .setSleepTime(1000)
                        .setTimeOut(10000);
            }

这里使用了xpath的语法来选取,不熟悉xpath的话,可以使用chrome:检查-copy-copy xpath来学习。

doc