介紹
jsoup 是一款Java的HTML解析器,可直接解析某個URL位址、HTML文本内容。它提供了一套非常省力的API,可通過DOM,CSS以及類似于jQuery的操作方法來取出和操作資料。
準備工作
建立一個java的項目,這裡我采用的是Maven項目,首先導入所需要的依賴包jsoup
<!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.11.3</version>
</dependency>
解析爬取内容
這裡我們爬取的是一個天氣預報的網址,為了能夠讓大家快速了解這個jsoup爬取的方法,這裡主要是通過爬取獲得廣州的今天天氣情況。
- 首先,檢查網頁源碼,發現這個代碼段

這裡框框裡面的是我們需要擷取的内容
編寫工具
- JsoupUtil.class – 連接配接url工具
- WeatherUtil.class – 擷取廣州天氣工具
實作步驟
- 編寫url工具,使用Document doc = Jsoup.connect(“http://example.com/”).get();擷取url連接配接
public class JsoupUtil {
/**
* 從一個url擷取
*/
public Document getDocument(String url) {
try {
return Jsoup.connect(url).get();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
- 編寫擷取天氣工具:
public class WeatherUtil {
/**
* 擷取廣州的今天天氣
*/
public String getWeather() {
//擷取url連接配接對象
JsoupUtil jsoupUtil = new JsoupUtil();
Document doc = jsoupUtil.getDocument("http://www.weather.com.cn/weather1d/101280101.shtml");
//擷取目标html代碼:查id為today的标簽元素
Elements elements = doc.select("[id=today]");
//擷取今天天氣:擷取input标簽的id為hidden_tile的元素,再擷取該元素的value屬性值
String weather = elements.select("input[id=hidden_title]").attr("value");
return weather;
}
}
- 最後測試是否成功
public class WeatherTest {
public static void main(String[] args) {
WeatherUtil weatherUtil = new WeatherUtil();
System.out.println(weatherUtil.getWeather());
}
}
參考資料
- jsoup官方中文文檔為:http://www.open-open.com/
- API為:http://jsoup.org/apidocs/
總結
主要是通過select定位到标簽元素,再結合JavaScript裡面的一些例如append()的方法找到所需的标簽,最後使用text()或其他方法擷取到内容,其他方法詳情可以參考上面的官方文檔。下一期我們來體驗編寫一個java工具:發送驗證碼到電子郵箱