7.2 入门案例

    技术2022-07-10  151

    下面,以抓取博客内容为例,介绍WebMagic的使用。 使用WebMagic采集数据,只需要编写一个爬虫类,实现PageProcessor接口,如程序7-1所示。Processor类实现了PageProcessor接口中的getSite()和process()方法。其中,getSite()方法用于配置网络爬虫,process()方法用来实现页面操作。 从程序7-1中,可以看到配置网络爬虫时需要使用Site类中的相关方法,如调用setRetryTimes()方法设置网页请求重试次数,调用setSleepTime()方法设置页面请求之间的时间间隔。 在process()方法中,首先通过URL判断请求的页面是博客列表页还是博客详情页,如果是列表页则使用Xpath语法抽取页面所有的列表页链接和详情页链接加入到待请求URL队列中。如果是博客详情页,则将该博客内容以HTML的格式存储在本地磁盘中。

    public class Processor implements PageProcessor { //博客列表页URL正则表达式 public static final String URL_LIST = "https://blog\\.csdn\\.net/Jgx1214/article/list/\\d"; //博客详情页URL正则表达式 public static final String URL_POST = "https://blog\\.csdn\\.net/Jgx1214/article/details/\\d{1,}"; //网络爬虫相关设置,这里设置了重试次数和采集休眠时间(单位为秒) private Site site = Site.me().setRetryTimes(3).setSleepTime(1); @Override public Site getSite() { return site; } //针对每个URL对应的页面进行操作 @Override public void process(Page page) { //处理需要采集的URL if (page.getUrl().regex(URL_LIST).match()) { //将当前页面所有列表页链接加入请求队列队尾 page.addTargetRequests(page.getHtml().xpath("//*[@id=\"mainBox\"]/main/div[2]").links().regex(URL_POST).all()); //将当前页面所有详情页链接加入请求队列队尾 page.addTargetRequests(page.getHtml().links().regex(URL_LIST).all()); } else {//解析和存储网页内容 try { //将采集的文章以HTML的格式存储到本地磁盘 Document document = page.getHtml().getDocument(); String title = document.select("#mainBox > main > div.blog-content-box > div > div > div.article-title-box > h1").text(); String str = document.html(); byte[] bytes = str.getBytes("utf-8"); //设置文件保存的路径和文件名称 FileOutputStream history = new FileOutputStream(PathConstant.basePath + "csdn/" + title + ".html"); history.write(bytes); history.close(); }catch (Exception e){ e.printStackTrace(); } } } public static void main(String[] args) { Spider.create(new Processor()) .addUrl("https://blog.csdn.net/Jgx1214/article/list/1")//爬虫的种子URL .thread(15)//开启15个线程抓取 .run();//开启爬虫 } }
    Processed: 0.018, SQL: 9