java实现简单的爬虫之今日头条
前言
需要提前说下的是,由于今日头条的文章的特殊性,所以无法直接获取文章的地址,需要获取文章的id然后在拼接成url再访问。下面话不多说了,直接上代码。
示例代码如下
publicclassDemo2{
publicstaticvoidmain(String[]args){
//需要爬的网页的文章列表
Stringurl="http://www.toutiao.com/news_finance/";
//文章详情页的前缀(由于今日头条的文章都是在group这个目录下,所以定义了前缀,而且通过请求获取到的html页面)
Stringurl2="http://www.toutiao.com/group/";
//链接到该网站
Connectionconnection=Jsoup.connect(url);
Documentcontent=null;
try{
//获取内容
content=connection.get();
}catch(IOExceptione){
e.printStackTrace();
}
//转换成字符串
StringhtmlStr=content.html();
//因为今日头条的文章展示比较奇葩,都是通过js定义成变量,所以无法使用获取dom元素的方式获取值
StringjsonStr=StringUtils.substringBetween(htmlStr,"var_data=",";");
System.out.println(jsonStr);
Mapparse=(Map)JSONObject.parse(jsonStr);
JSONArrayparseArray=(JSONArray)parse.get("real_time_news");
Mapmap=null;
List<Map>maps=newArrayList<>();
//遍历这个jsonArray,获取到每一个json对象,然后将其转换成Map对象(在这里其实只需要一个group_id,那么没必要使用map)
for(inti=0;i<parseArray.size();i++){
map=(Map)parseArray.get(i);
maps.add((Map)parseArray.get(i));
System.out.println(map.get("group_id"));
}
//遍历之前获取到的map集合,然后分别访问这些文章详情页
for(Mapmap2:maps){
connection=Jsoup.connect(url2+map2.get("group_id"));
try{
Documentdocument=connection.get();
//获取文章标题
Elementstitle=document.select("[class=article-title]");
System.out.println(title.html());
//获取文章来源和文章发布时间
ElementsarticleInfo=document.select("[class=articleInfo]");
Elementssrc=articleInfo.select("[class=src]");
System.out.println(src.html());
Elementstime=articleInfo.select("[class=time]");
System.out.println(time.html());
//获取文章内容
ElementscontentEle=document.select("[class=article-content]");
System.out.println(contentEle.html());
}catch(IOExceptione){
e.printStackTrace();
}
}
}
}
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。