1.引入maven依賴
<!-- jsoup -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.10.2</version>
</dependency>
2.代碼
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
public class JsoupTest {
/**
* 讀HTML文件
* @param pathname
* @return
*/
public static String readHtml(String path) {
StringBuffer buff = new StringBuffer();
// 建立一個對象,它把文件內容轉成計算機能讀懂的語言
try (FileReader reader = new FileReader(path); BufferedReader br = new BufferedReader(reader)) {
String line;
int count = 0;
while ((line = br.readLine()) != null) {
// 一次讀入一行數據
buff.append(line);
count++;
}
} catch (IOException e) {
e.printStackTrace();
}
return buff.toString();
}
/**
* jsoup方法中 text() :用於獲取獲取標籤的文本 html() :獲取標籤裏面的所有字符串包括html標籤
* attr(attributeKey)獲取屬性裏面的值,參數是屬性名稱
*/
public static void main(String[] args) {
try {
// 本地html存放路徑
String file_path = "D:\\index.html";
// 讀取html獲取文檔
String html = readHtml(file_path);
Document document = Jsoup.parse(html);
// 通過select獲取元素
// 一個頁面中的class可能會重複,爲避免取多餘的數據,
// 先取部分區域的數據,然後再從這部分區域數據中取出真正需要的數據
////格式: class用"#"、id用"."、標籤用h1 例如: div.title_area>h1
Elements div = document.select(".content_18313");// 外層部分區域標籤內的數據
Elements title = div.select(".title_area>h1");// 真正需要標籤內的數據
System.out.println("打印最終結果:" + title.text());
} catch (Exception e) {
e.printStackTrace();
}
}
}