最近看之前写的几篇网页数据采集的博客,陆陆续续的有好友发私信交流,又想重新整理一下这些了,抽空继续更新本系列博客。
针对开源中国新闻列表新版,重新写代码抓取。
网址:https://www.oschina.net/news jar包:jsoup.1.7.2.jar 项目源码:https://github.com/geekfly2016/Spider
<div class="news-list-item" id="all-news">
<!--文章列表-->
</div>
<div class="item box"></div>
Elements items = document.select("#all-news .item");
System.out.println(items.size());
注:因为class有两个,item和box,由于Jsoup选择器中需写两个select,此处使用一个即可精确匹配。可参看:http://blog.csdn.net/ywf008/article/details/53215648
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;
}
注:抓取时打印链接发现部分链接已为完整的,有些许自行拼接域名,故此处加了判断是否已https://开始。
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;
}
仓库:https://github.com/geekfly2016/Spider 代码目录:Spider/src/xyz/geekfly/oschina/News.java
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有