admin管理员组文章数量:1660818
前言
需要提前说下的是,由于今日头条的文章的特殊性,所以无法直接获取文章的地址,需要获取文章的id然后在拼接成url再访问。下面话不多说了,直接上代码。
示例代码如下
public class Demo2 {
public static void main(String[] args) {
// 需要爬的网页的文章列表
String url = "http://www.toutiao/news_finance/";
//文章详情页的前缀(由于今日头条的文章都是在group这个目录下,所以定义了前缀,而且通过请求获取到的html页面)
String url2="http://www.toutiao/group/";
//链接到该网站
Connection connection = Jsoup.connect(url);
Document content = null;
try {
//获取内容
content = connection.get();
} catch (IOException e) {
e.printStackTrace();
}
//转换成字符串
String htmlStr = content.html();
//因为今日头条的文章展示比较奇葩,都是通过js定义成变量,所以无法使用获取dom元素的方式获取值
String jsonStr = StringUtils.substringBetween(htmlStr,"var _data = ", ";");
System.out.println(jsonStr);
Map parse = (Map) JSONObject.parse(jsonStr);
JSONArray parseArray = (JSONArray) parse.get("real_time_news");
Map map=null;
List maps=new ArrayList<>();
//遍历这个jsonArray,获取到每一个json对象,然后将其转换成Map对象(在这里其实只需要一个group_id,那么没必要使用map)
for(int i=0;i
map = (Map)parseArray.get(i);
maps.add((Map)parseArray.get(i));
System.out.println(map.get("group_id"));
}
//遍历之前获取到的map集合,然后分别访问这些文章详情页
for (Map map2 : maps) {
connection = Jsoup.connect(url2+map2.get("group_id"));
try {
Document document = connection.get();
//获取文章标题
Elements title = document.select("[class=article-title]");
System.out.println(title.html());
//获取文章来源和文章发布时间
Elements articleInfo = document.select("[class=articleInfo]");
Elements src = articleInfo.select("[class=src]");
System.out.println(src.html());
Elements time = articleInfo.select("[class=time]");
System.out.println(time.html());
//获取文章内容
Elements contentEle = document.select("[class=article-content]");
System.out.println(contentEle.html());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。
版权声明:本文标题:java新闻爬虫_java实现简单的爬虫之今日头条 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/xitong/1729881722a1216004.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论