萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

jsoup 入門到精通:Java 端 HTML 解析、選擇器、資料清洗與反爬蟲實戰

為什麼選 jsoup?

  • 單一 JAR、零依賴、Maven Central 即時可用。
  • API 直覺:支援 CSS 選擇器、類 jQuery 鏈式呼叫、DOM 遍歷。
  • 容錯性強:自動修補斷裂標籤、處理編碼、支援 HTML5。
  • MIT 授權,商業專案免費使用。

Maven 依賴

<dependency>
  <groupId>org.jsoup</groupId>
  <artifactId>jsoup</artifactId>
  <version>1.17.2</version> <!-- 檢查最新版 -->
</dependency>

三大入口:URL、File、String

// 1. 直接抓取網頁
Document doc = Jsoup.connect("https://example.com")
  .userAgent("Mozilla/5.0")          // 模擬瀏覽器
  .timeout(10_000)                   // 10 秒逾時
  .get();

// 2. 解析本地檔案
Document doc = Jsoup.parse(new File("page.html"), "UTF-8", "https://example.com/");

// 3. 解析字串片段
Document doc = Jsoup.parseBodyFragment("<p>片段</p>"); // 無 html/head/body

選擇器語法速查(CSS Selector)

// 基礎
doc.select("div")              // 所有 div
doc.select("#main")            // id=main
doc.select(".card")            // class=card
doc.select("article > header") // 直接子元素
doc.select("ul li")            // 後代

// 屬性
doc.select("a[href]")                    // 有 href 的 a
doc.select("img[src$=.png]")             // src 以 .png 結尾
doc.select("input[type=checkbox]:checked") // 被勾選的 checkbox

// 偽類
doc.select("tr:eq(0)")      // 第 1 列
doc.select("tr:lt(3)")      // 前 3 列
doc.select("p:contains(關鍵字)") // 含特定文字
doc.select(":not(.ad)")     // 排除 .ad

資料提取與操作實戰

// 提取標題、連結、圖片
Elements links = doc.select("a[href]");
for (Element link : links) {
  String url = link.attr("abs:href"); // 自動轉絕對路徑
  String text = link.text();
  System.out.println(text + " → " + url);
}

// 修改 DOM
doc.select("script, style, .ad, nav").remove(); // 移除雜訊
doc.select("img").attr("loading", "lazy");      // 加入 lazy loading
String cleanHtml = doc.body().html();           // 取得淨化後 HTML

反爬蟲應對策略

  • 設定合理 User-Agent、Referer、Cookie。
  • 使用 Connection.Response 管理 Session Cookie。
  • 隨機延遲 Thread.sleep(random(1000,3000))。
  • IP 池輪換、Headless Browser (Playwright/Puppeteer) 處理 JS 渲染頁面。
  • 遵守 robots.txt、Rate Limit、法律法規。

常見陷阱

  • 編碼偵測失敗 → 指定 .charset("UTF-8") 或檢查 Content-Type header。
  • 大文件 OOM → 使用 Jsoup.parse(html, baseUri, Parser.xmlParser()) 流式處理或分塊。
  • 選擇器效能 → 避免過深後代選擇器,優先用 ID/Class 定位。
copyright © 萬盛學電腦網 all rights reserved