WebCollector抓取美团技术文章案例
package com.forezp; import cn.edu.hfut.dmic.webcollector.model.CrawlDatums; import cn.edu.hfut.dmic.webcollector.model.Page; import cn.edu.hfut.dmic.webcollector.plugin.rocks.BreadthCrawler; import java.io.*; import java.util.regex.Pattern; /*** * 获取数据写入txt文件 */ public class GetNewsInfo extends BreadthCrawler { /** * 重写构造函数 * @param crawlPath 爬虫路径 * @param autoParse 是否自动解析 */ public GetNewsInfo(String crawlPath, boolean autoParse) { super(crawlPath, autoParse); } @Override public void visit(Page page, CrawlDatums next) { // 继承覆盖visit方法,该方法表示在每个页面进行的操作 // 参数page和next分别表示当前页面和下个URL对象的地址 String news_regex = "https://tech.meituan.com/2022/09/.*"; // 对页面进行正则判断,如果有的话,将网页标题提取出来,否则不进行任何操作 if (Pattern.matches(news_regex, page.url())) { // 将网页的URL和网页标题提取出来 String url = page.url(); String title = page.select("title").first().text(); String content=page.select("div[class=post-content]").text(); System.out.println(url); System.out.println(title); System.out.println(content); File file=new File(title+".txt"); try { BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true))); out.write(content); out.close(); }catch (Exception e){ } } } public static void main(String[] args) throws Exception{ GetNewsInfo crawler = new GetNewsInfo("crawler", true); // 添加初始种子页面 crawler.addSeed("https://tech.meituan.com/"); // 设置采集规则为所有类型的网页 crawler.addRegex("https://tech.meituan.com/2022/09/.*"); // 设置爬取URL数量的上限 // 设置线程数 crawler.setThreads(1); // 设置断点采集 crawler.setResumable(false); // 设置爬虫深度 crawler.start(2); } }
引入pom.xml
<dependency> <groupId>cn.edu.hfut.dmic.webcollector</groupId> <artifactId>WebCollector</artifactId> <version>2.73-alpha</version> </dependency>
好记性不如烂笔头
浙公网安备 33010602011771号