java簡單的爬蟲(今日頭條)

zhumeilu發表於2017-12-14

之前在做資訊站的時候需要用到爬蟲來獲取一些文章,今天剛好有空就研究了一下.在網上看到了一個demo,使用的是Jsoup,我拿過來修改了一下, 由於今日頭條的文章的特殊性,所以無法直接獲取文章的地址,需要獲取文章的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();
		}
	}
 }
}
複製程式碼

相關文章