Java实现网络爬虫 案例代码

Java实现网络爬虫 案例代码


需求说明

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

 

步骤分析

访问网址: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();
}
}

posted @   xmx测试员  阅读(152)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示