抓取网页新闻(针对开源中国新闻列表新版重新写代码抓取(抓取))

优采云 发布时间: 2022-01-28 22:12

  抓取网页新闻(针对开源中国新闻列表新版重新写代码抓取(抓取))

  最近看了几篇之前写的关于网络数据采集的博文,朋友们纷纷私信交流,想重新整理一下。有时间我会继续更新这个系列的博客。

  对于新版开源中国新闻榜,重新编写代码进行爬取。

  网址:

  jar包:jsoup.1.7.2.jar

  项目源代码:

  

  Elements items = document.select("#all-news .item");

System.out.println(items.size());

  注意:因为有两个类,item和box,并且因为Jsoup选择器中需要写两个select,所以这里可以使用一个进行精确匹配。看:

  String title = item.select("a").first().text();

String title_href = item.select("a").first().attr("href");

if(!title_href.startsWith("https://")){

title_href = host + title_href;

}

  注意:爬取的时候打印链接,发现有的链接是完整的,有的域名是自己拼接的,所以这里加上判断。

  String desc = item.select("div[class=sc sc-text text-gradient wrap summary]").text();

  当一个属性有多个值时,除了使用某个值或使用上面提到的多个select选择器外,还可以使用div[class=xx yy zz]模式匹配(推荐)。

  String author_image = item.select("img[class=avatar]").attr("src");

  或者

  String author_image = item.select("img").first().attr("src");

  不是获得它的唯一方法

  Element mr = item.select(".from .mr").get(0);

//作者

String author = mr.select("a").text();

// 从span[class=mr]中移除a标签,输出的即为发布时间

mr.select("a").remove();

String published = mr.text();

  String number = item.select(".from .mr").last().text();

  至此,我们可以完整获取当前页面的新闻数据。

  注:新闻列表数据收录一条广告数据

  

  //过滤广告

if(!item.attr("data-tracepid").isEmpty()){

continue;

}

  库:

  代码目录:Spider/src/xyz/geekfly/oschina/News.java

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线