前言
需要提前说下的是,由于今日头条的文章的特殊性,所以无法直接获取文章的地址,需要获取文章的id然后在拼接成url再访问。下面话不多说了,直接上代码。
示例代码如下
public class Demo2 {
public static void main(String[] args) {
// 需要爬的网页的文章列表
String url = "http://www.toutiao.com/news_finance/";
//文章详情页的前缀(由于今日头条的文章都是在group这个目录下,所以定义了前缀,而且通过请求获取到的html页面)
String url2="http://www.toutiao.com/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


