package net.chinaedu.utils;import java.io.IOException;import java.util.ArrayList;import java.util.List;import org.jsoup.Jsoup;import org.jsoup.nodes.Document;import org.jsoup.nodes.Element;import org.jsoup.select.Elements;import net.chinaedu.bean.Phone;/** * 使用Jsoup進行爬蟲,并且將資料決議出來,封裝到Phone物件中,存盤到List集合中 * * @author Administrator * */public class JsoupUtils { /** * 得到指定鏈接的原始碼,并且轉成Document檔案物件回傳 * * @param url * @return * @throws IOException */ public static Document getHtmlDocument(String url) throws IOException { // 爬取網頁原始碼,得到檔案物件 Document document = Jsoup.connect(url).get(); // 將網頁檔案物件回傳 return document; } /** * 決議網頁,將決議出來的內容先封裝到Phone物體類中,然后保持到List集合中,并且回傳 * * @param document * @return */ public static List<Phone> getPhoneList(Document document) { // 1.定義一個可以存放Phone物件的集合物件 List<Phone> phoneList = new ArrayList<Phone>(); // 2.開始決議檔案 // 2.1通過標簽的屬性得到多個標簽元素 Elements elements = document.getElementsByAttribute("data-follow-id"); // 2.2遍歷多個標簽物件 for (int i = 0; i < elements.size(); i++) { // 2.3得到每一個標簽元素 Element element = elements.get(i); // 2.4獲取Phone物件的每一個屬性值 // 2.4.1獲取手機名稱 /* * getElementsByTag("img"):得到img標簽 * attr("alt"):得到alt屬性的值 */ String name = element.getElementsByTag("img").attr("alt"); // 2.4.2得到配置 String config = element.getElementsByTag("span").first().text(); // 2.4.3得到價格 String priceStr = element.getElementsByClass("price-type").text(); // 將字串的價格轉成double型別的價格 /* * Double.parseDouble(priceStr):將字串類的小數轉成double * Integer.parseInt(intStr):將字串的整數轉成int */ double price = (priceStr == null) ? 0 : Double.parseDouble(priceStr); // 2.4.4得到評分 String scoreStr = element.getElementsByClass("score").text(); // 將字串的評分轉成double型別的評分 double score = (scoreStr == null) ? 0 : Double.parseDouble(scoreStr); // 2.4.5得到點評數 String numStr = element.getElementsByClass("comment-num").text(); // 獲取點評數字串中的數字 int num = StringUtils.getNumByString(numStr); // 2.4.6得到熱門排行榜 String rank = element.getElementsByClass("rank-row").text(); // 2.4.7得到手機的圖片 String img = element.getElementsByTag("img").first().attr(".src"); // 2.5使用上面的七個值構建 Phone phone = new Phone(name, config, price, score, num, rank, img); // 2.7將phone保持到集合中 phoneList.add(phone);
// 2.8將圖片下載到本地
// 輸出日志
System.out.println("【" + name + "】爬取完成...."); }
// 回傳集合物件
return phoneList; }}

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/227251.html
標籤:Eclipse
上一篇:8、Spring Boot任務
下一篇:有大神能幫忙嗎
