ITPub博客

首页 > 数据库 > Oracle > Java实现网络爬虫 案例代码

Java实现网络爬虫 案例代码

原创 Oracle 作者:新梦想IT 时间:2022-11-22 15:54:31 0 删除 编辑

Java实现网络爬虫 案例代码4:使用webmagic框架从网上获取《三国演义》全文



需求说明


搭建开发环境,实现《三国演义》全文保存在本地




步骤分析


访问网址:http://www.shicimingju.com/book/sanguoyanyi.html


分析网站URL、文档内容特征


获取网页内容


拆分出需求内容


保存在本地




案例代码


import us.codecraft.webmagic.Page;

import us.codecraft.webmagic.Site;

import us.codecraft.webmagic.Spider;

import us.codecraft.webmagic.pipeline.ConsolePipeline;

import us.codecraft.webmagic.pipeline.FilePipeline;

import us.codecraft.webmagic.pipeline.JsonFilePipeline;

import us.codecraft.webmagic.processor.PageProcessor;


public class NovelRepoPageProcessor implements PageProcessor {

    // 部分一:抓取网站的相关配置,包括编码、抓取间隔、重试次数等

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


    @Override

    // process是定制爬虫逻辑的核心接口,在这里编写抽取逻辑

    public void process(Page page) {

        // 部分二:定义如何抽取页面信息,并保存下来  http://www.shicimingju.com/book/sanguoyanyi/

        page.putField("id", page.getUrl().

        regex("http://www\\.shicimingju\\.com/book/sanguoyanyi/(\\d+)\\.html").toString());

        page.putField("name", 

            page.getHtml().xpath("//h1/text()").toString());

        if (page.getResultItems().get("name") == null) {

            //skip this page

            page.setSkip(true);

        }

        //<div class="chapter_content">

        page.putField("content", 

        page.getHtml().xpath("//div[@class='chapter_content']/tidyText()"));


        // 部分三:从页面发现后续的url地址来抓取

        page.addTargetRequests(page.getHtml().links().

                regex("(http://www\\.shicimingju\\.com/book/sanguoyanyi/(\\d+)\\.html)").all());

    }


    @Override

    public Site getSite() {

        return site;

    }


    public static void main(String[] args) {


        Spider.create(new NovelRepoPageProcessor())

                //从"http://www.shicimingju.com/book/sanguoyanyi.html"开始抓

                .addUrl("http://www.shicimingju.com/book/sanguoyanyi.html")

                .addPipeline(new JsonFilePipeline("D:\\webmagic\\"))  //JSON格式保存结果到文件

                //开启5个线程抓取

                .thread(5)

                //启动爬虫

                .run();

    }

}


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69940641/viewspace-2924582/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
新梦想IT职业教育(新梦想软件测试),是长沙一家专注于IT教育培训的机构。分享干货不容易,如果想了解更多的软件测试精彩干货,请留言交流,感谢阅读!

注册时间:2019-07-11

  • 博文量
    237
  • 访问量
    140202