WebMagic爬取网页信息
程序员文章站
2022-05-02 20:48:51
...
package cc.mrbird.febs.system.collection.cs;
import cc.mrbird.febs.common.utils.StringUtils;
import cc.mrbird.febs.system.collection.MysqlPipeline;
import cc.mrbird.febs.system.collection.rmw.RmwCollection;
import cc.mrbird.febs.system.entity.CjData;
import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.scheduler.BloomFilterDuplicateRemover;
import us.codecraft.webmagic.scheduler.QueueScheduler;
import us.codecraft.webmagic.selector.Selectable;
import java.util.Date;
import java.util.List;
@Component
public class CsCollection implements PageProcessor {
@Autowired
private MysqlPipeline mysqlPipeline;
// 抓取网站的相关配置,包括编码、抓取间隔、重试次数等
private Site site = Site.me().setRetryTimes(3).setSleepTime(100);
private String url = "https://www.casl.org.cn/policy/getByPolicy/zcfg";
@Override
public Site getSite() {
return site;
}
@Override
public void process(Page page) {
//文章详情链接正则表达式/html/body/div[4]/div[2]/div[1]/div[1]/a/div[3]/h2
String describeLink = "http://localhost:8080/policy/selectDetail/\\d{3}";
//文章标题/html/body/div[4]/div[1]
String titleXpath = "/html/body/div[4]/div[1]/text()";
//文章来源/html/body/div[4]/div[2]/div[1]/span[2]
String sourceXpath = "/html/body/div[4]/div[2]/div[1]/span[2]/text()";
//发布时间
String publishTime="/html/body/div[4]/div[2]/div[1]/span[1]/text()";
String lbPublishTime ="/html/body/div[4]/div[2]/div[1]/div[1]/a/div[3]/p[2]/span";
//判断是列表页还是详情页
List<Selectable> listurl = page.getHtml().css("div.zcwj_con div.zcwj_list div.hui").nodes();
if (listurl.size() == 0) {//详情页
String sourceStr=page.getHtml().xpath(sourceXpath).regex(".*原创.*").toString();
if(sourceStr!=null && !sourceStr.equals("")){
CjData cjData=new CjData();
cjData.setTitle(page.getHtml().xpath(titleXpath).toString());
String publishStr=page.getHtml().xpath(publishTime).toString();
cjData.setPublishTime(publishStr);
cjData.setSource(page.getHtml().xpath(sourceXpath).toString());
cjData.setContext(Jsoup.parse(page.getHtml().css("div#content1").toString()).text());
cjData.setUrl(page.getUrl().toString());
cjData.setCreateTime(new Date());
page.putField("cjData",cjData);
}
} else {
//如果是列表页
//获取列表页所有文章的url
for (Selectable selectable : listurl) {
String strurl = selectable.links().toString();
page.addTargetRequest(strurl);
}
}
}
public void process() {
Spider.create(new CsCollection())
.addUrl(url)
.setScheduler(new QueueScheduler().setDuplicateRemover(new BloomFilterDuplicateRemover(1000000)))//url去重
.addPipeline(this.mysqlPipeline)
.thread(3)
.run();
}
}
上一篇: 哪些明星离婚后才知道他们是夫妻
下一篇: 还忘不掉前任,该怎么和狮子座复合呢?