前言
需要提前說下的是,由於今日頭條的文章的特殊性,所以無法直接獲取文章的地址,需要獲取文章的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<Map> maps=new ArrayList<>(); //遍歷這個jsonArray,獲取到每一個json對象,然後將其轉換成Map對象(在這裡其實只需要一個group_id,那麼沒必要使用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集合,然後分別訪問這些文章詳情頁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(); } } }}總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流。