之前在做資訊站的時(shí)候需要用到爬蟲來(lái)獲取一些文章,今天剛好有空就研究了一下.在網(wǎng)上看到了一個(gè)demo,使用的是Jsoup,我拿過(guò)來(lái)修改了一下,
由于今日頭條的文章的特殊性,所以無(wú)法直接獲取文章的地址,需要獲取文章的id然后在拼接成url再訪問(wèn).
public class Demo2 {
public static void main(String[] args) {
// 需要爬的網(wǎng)頁(yè)的文章列表
String url = "http://www.toutiao.com/news_finance/";
//文章詳情頁(yè)的前綴(由于今日頭條的文章都是在group這個(gè)目錄下,所以定義了前綴,而且通過(guò)請(qǐng)求獲取到的html頁(yè)面)
String url2="http://www.toutiao.com/group/";
//鏈接到該網(wǎng)站
Connection connection = Jsoup.connect(url);
Document content = null;
try {
//獲取內(nèi)容
content = connection.get();
} catch (IOException e) {
e.printStackTrace();
}
//轉(zhuǎn)換成字符串
String htmlStr = content.html();
//因?yàn)榻袢疹^條的文章展示比較奇葩,都是通過(guò)js定義成變量,所以無(wú)法使用獲取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<Map> maps=new ArrayList<>();
//遍歷這個(gè)jsonArray,獲取到每一個(gè)json對(duì)象,然后將其轉(zhuǎn)換成Map對(duì)象(在這里其實(shí)只需要一個(gè)group_id,那么沒(méi)必要使用map)
for(int i=0;i<parseArray.size();i++){
map = (Map)parseArray.get(i);
maps.add((Map)parseArray.get(i));
System.out.println(map.get("group_id"));
}
//遍歷之前獲取到的map集合,然后分別訪問(wèn)這些文章詳情頁(yè)
for (Map map2 : maps) {
connection = Jsoup.connect(url2+map2.get("group_id"));
try {
Document document = connection.get();
//獲取文章標(biāo)題
Elements title = document.select("[class=article-title]");
System.out.println(title.html());
//獲取文章來(lái)源和文章發(fā)布時(shí)間
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());
//獲取文章內(nèi)容
Elements contentEle = document.select("[class=article-content]");
System.out.println(contentEle.html());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}