?Jsoup:HTML解析利器
-
定位:專注HTML解析的輕量級庫(也就是快,但動態頁面無法抓取)
-
核心能力:
-
DOM樹解析與CSS選擇器查詢
-
HTML凈化與格式化
-
支持元素遍歷與屬性提取
-
-
應用場景:靜態頁面數據抽取、內容清洗
public static Document getJsoupDoc(String url, Integer frequency, Integer connectTimeout) {Document document = null;try {if(connectTimeout==null){document = Jsoup.connect(url).ignoreContentType(true).get();}else{document = Jsoup.connect(url).ignoreContentType(true).maxBodySize(0).timeout(connectTimeout).get();}} catch (Exception e) {document = null;}if (document == null && frequency < 3) {frequency = frequency + 1;try {Thread.sleep(100);} catch (InterruptedException e) {log.error("休眠異常:" + e.getMessage(), e);}document = getJsoupDoc(url, frequency, connectTimeout);}return initUrl(url,document);}
?HtmlUnit:無頭瀏覽器引擎
-
定位:支持JavaScript的全功能瀏覽器模擬器(js動態數據的加載)
-
核心能力:
-
執行復雜AJAX請求
-
模擬用戶交互(點擊/表單提交)
-
支持Cookie管理和頁面跳轉
-
-
典型場景:動態網頁抓取、自動化測試
/*** @param url 爬蟲鏈接* @param waitTime 等待時間* @return*/public static Document getDynamicCrawlersDocument(String url, Integer waitTime, boolean javaScriptEnabled) {Document document = null;try (WebClient browser = new WebClient()) {//解決動態頁面抓取不到信息問題browser.getOptions().setCssEnabled(false);browser.getOptions().setJavaScriptEnabled(javaScriptEnabled);browser.getOptions().setThrowExceptionOnScriptError(false);browser.getOptions().setUseInsecureSSL(true);// 設置自定義的錯誤處理類browser.setJavaScriptErrorListener(new MyJSErrorListener());HtmlPage page = null;page = browser.getPage(url);// 等待后臺腳本執行時間browser.waitForBackgroundJavaScript(waitTime);String pageAsXml = page.asXml();document = Jsoup.parse(pageAsXml.replaceAll("\\<\\?xml.*?\\?>", ""));document.setBaseUri(url);} catch (ScriptException e) {log.error("getDynamicCrawlersDocument頁面:{} JavaScript 異常:{}", url, e.getMessage());return initUrl(url,document);} catch (UnknownHostException e) {log.error("getDynamicCrawlersDocument頁面:{} 無法解析或找到指定的主機名:{}", url, e.getMessage());return initUrl(url,document);} catch (FailingHttpStatusCodeException e) {log.error("getDynamicCrawlersDocument頁面:{} HTTP 狀態異常:{}", url, e.getStatusCode());return initUrl(url,document);} catch (Exception e) {log.error("getDynamicCrawlersDocument頁面:{} 獲取頁面異常:{}", url, e.getMessage());return initUrl(url,document);}return initUrl(url,document);}
核心優勢對比
特性 Jsoup HtmlUnit 解析速度 ?? 毫秒級響應 ? 需加載完整頁面資源 JS支持 ? 不執行任何腳本 ? 完整JavaScript引擎 內存占用 🟢 10MB級內存消耗 🔴 100MB+內存需求 學習曲線 🟢 半天掌握核心API 🟡 需理解瀏覽器事件模型 反爬繞過 ? 基礎Header支持 ? 模擬真實瀏覽器指紋 -
實戰場景選擇指南
? 首選Jsoup的情況
-
目標數據存在于初始HTML中(靜態頁面)
-
需要高頻抓取(>1000次/分鐘)
-
服務器資源受限(云函數/邊緣計算)
-
快速原型開發需求
-
-
? 必須HtmlUnit的場景
-
頁面依賴AJAX動態加載(js數據請求)
-
需要登錄Cookie保持
-
涉及表單交互操作
-
需解析Shadow DOM內容
-
-
結語
Jsoup與HtmlUnit代表了Java爬蟲的兩個技術維度:極致效率與完整模擬。理解二者的設計哲學,根據實際場景靈活選用甚至組合使用(如用HtmlUnit獲取初始頁面后用Jsoup解析),往往能取得最佳效果。在日益復雜的反爬機制下,合理選擇工具將成為數據抓取成功的關鍵。
完整代碼工具類
package com.zzkj.zei.utils;import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.zzkj.zei.pojo.system.SysSite;
import com.zzkj.zei.utils.spider.SpiderUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.htmlunit.BrowserVersion;
import org.htmlunit.FailingHttpStatusCodeException;
import org.htmlunit.ScriptException;
import org.htmlunit.WebClient;
import org.htmlunit.html.HtmlAnchor;
import org.htmlunit.html.HtmlPage;
import org.htmlunit.javascript.DefaultJavaScriptErrorListener;
import org.jetbrains.annotations.NotNull;
import org.jsoup.HttpStatusException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;import java.io.IOException;
import java.net.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;/*** FileName: JsoupHtmlUintUtils* Author: wzk* Date:2024/11/8 9:32*/
@Slf4j
public class JsoupHtmlUintUtils {/*** 動態檢測** @param url 爬蟲鏈接* @return*/public static Document getDynamicCrawlersDocument(String url) {Document document = null;//解決動態頁面抓取不到信息問題WebClient browser = new WebClient(BrowserVersion.CHROME);browser.getOptions().setCssEnabled(false);browser.getOptions().setJavaScriptEnabled(false);browser.getOptions().setThrowExceptionOnScriptError(false);// 允許使用不安全的 SSLbrowser.getOptions().setUseInsecureSSL(true);// 設置自定義的錯誤處理類browser.setJavaScriptErrorListener(new MyJSErrorListener());HtmlPage page = null;try {page = browser.getPage(url);// 等待后臺腳本執行時間browser.waitForBackgroundJavaScript(1000);String pageAsXml = page.asXml();document = Jsoup.parse(pageAsXml);} catch (ScriptException e) {log.info("頁面:{} JavaScript 異常:{}", url, e.getMessage());} catch (FailingHttpStatusCodeException e) {log.info("頁面:{} HTTP 狀態異常:{}", url, e.getStatusCode());} catch (UnknownHostException e) {log.info("頁面:{} 無法解析或找到指定的主機名:{}", url, e.getMessage());} catch (Exception e) {log.error("頁面:{} 獲取頁面異常:{}", url, e.getMessage());}return initUrl(url,document);}/*** @param url 爬蟲鏈接* @param waitTime 等待時間* @return*/public static Document getDynamicCrawlersDocument(String url, Integer waitTime, boolean javaScriptEnabled) {Document document = null;try (WebClient browser = new WebClient()) {//解決動態頁面抓取不到信息問題browser.getOptions().setCssEnabled(false);browser.getOptions().setJavaScriptEnabled(javaScriptEnabled);browser.getOptions().setThrowExceptionOnScriptError(false);browser.getOptions().setUseInsecureSSL(true);// 設置自定義的錯誤處理類browser.setJavaScriptErrorListener(new MyJSErrorListener());HtmlPage page = null;page = browser.getPage(url);// 等待后臺腳本執行時間browser.waitForBackgroundJavaScript(waitTime);String pageAsXml = page.asXml();document = Jsoup.parse(pageAsXml.replaceAll("\\<\\?xml.*?\\?>", ""));document.setBaseUri(url);} catch (ScriptException e) {log.error("getDynamicCrawlersDocument頁面:{} JavaScript 異常:{}", url, e.getMessage());return initUrl(url,document);} catch (UnknownHostException e) {log.error("getDynamicCrawlersDocument頁面:{} 無法解析或找到指定的主機名:{}", url, e.getMessage());return initUrl(url,document);} catch (FailingHttpStatusCodeException e) {log.error("getDynamicCrawlersDocument頁面:{} HTTP 狀態異常:{}", url, e.getStatusCode());return initUrl(url,document);} catch (Exception e) {log.error("getDynamicCrawlersDocument頁面:{} 獲取頁面異常:{}", url, e.getMessage());return initUrl(url,document);}return initUrl(url,document);}private static List<Document> getDynamicCrawlersDocument(String url, Integer waitTime) {List<Document> documents = new ArrayList<>();HtmlPage oldPage = null;try (WebClient browser = new WebClient()) {//解決動態頁面抓取不到信息問題browser.getOptions().setCssEnabled(false);browser.getOptions().setJavaScriptEnabled(true);browser.getOptions().setThrowExceptionOnScriptError(false);browser.getOptions().setUseInsecureSSL(true);// 設置自定義的錯誤處理類browser.setJavaScriptErrorListener(new MyJSErrorListener());HtmlPage page = null;page = browser.getPage(url);oldPage = page;// 等待后臺腳本執行時間browser.waitForBackgroundJavaScript(waitTime);Document document;document = getDocuments(url, page);documents.add(document);while (true) {HtmlAnchor nextButton = page.getFirstByXPath("//a[contains(text(), '下一頁')]");if (nextButton == null || nextButton.getAttribute("class").contains("disabled")) {break; // No more pages}page = nextButton.click();browser.waitForBackgroundJavaScript(waitTime);if (page.equals(oldPage) && !page.getUrl().toString().equals(url)) {break;}oldPage = page;document = getDocuments(url, page);documents.add(document);}} catch (ScriptException e) {log.error("getDynamicCrawlersDocument頁面:{} JavaScript 異常:{}", url, e.getMessage());} catch (UnknownHostException e) {log.error("getDynamicCrawlersDocument頁面:{} 無法解析或找到指定的主機名:{}", url, e.getMessage());} catch (FailingHttpStatusCodeException e) {log.error("getDynamicCrawlersDocument頁面:{} HTTP 狀態異常:{}", url, e.getStatusCode());} catch (Exception e) {log.error("getDynamicCrawlersDocument頁面:{} 獲取頁面異常:{}", url, e.getMessage());}return documents;}private static @NotNull Document getDocuments(String url, HtmlPage page) {String pageAsXml = page.asXml();Document document = Jsoup.parse(pageAsXml.replaceAll("\\<\\?xml.*?\\?>", ""));document.setBaseUri(url);return initUrl(url,document);}public static List<Document> getDocuments(String url, Integer isDynamic) {List<Document> list;if (isDynamic == 1) {list = getDynamicCrawlersDocument(url, 1000);} else {list = getJsoupDoc(url);}return list;}public static Document getDocument(String url, Integer isDynamic) {Document document;if (isDynamic == 1) {document = getDynamicCrawlersDocument(url, 1000, true);} else {document = getJsoupDoc(url, 1, null);}return initUrl(url,document);}/*** @param url 爬蟲鏈接* @return*/public static Document getJsoupDoc(String url, Integer frequency, Integer connectTimeout) {Document document = null;try {if(connectTimeout==null){document = Jsoup.connect(url).ignoreContentType(true).get();}else{document = Jsoup.connect(url).ignoreContentType(true).maxBodySize(0).timeout(connectTimeout).get();}} catch (Exception e) {document = null;}if (document == null && frequency < 3) {frequency = frequency + 1;try {Thread.sleep(100);} catch (InterruptedException e) {log.error("休眠異常:" + e.getMessage(), e);}document = getJsoupDoc(url, frequency, connectTimeout);}return initUrl(url,document);}private static List<Document> getJsoupDoc(String url) {List<Document> list = new ArrayList<>();Document document = getJsoupDoc(url, 1, null);list.add(document);return list;}public static String getRedirectUrl(String url) {log.info("getRedirectUrl-------------------url---------------" + url);String redirectUrl = "";//設置模擬瀏覽器try (WebClient webClient = new WebClient(BrowserVersion.CHROME)) {//是否等待頁面javaScrpit加載webClient.getOptions().setJavaScriptEnabled(true);webClient.getOptions().setRedirectEnabled(true);// js運行錯誤時,是否拋出異常webClient.getOptions().setThrowExceptionOnScriptError(false);webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);// 設置連接超時時間webClient.getOptions().setTimeout(200);// HtmlUnitredirectUrl = webClient.getPage(url).getUrl().toString();} catch (FailingHttpStatusCodeException | IOException e) {log.error(url + "獲取重定向網站失敗1:" + e.getMessage(), e);} catch (Exception e) {log.error(url + "獲取重定向網站失敗2:" + e.getMessage(), e);}return redirectUrl;}/*** 獲取重定向url** @param hrefUrl 鏈接地址* @param metaTagsUrl 元標簽地址* @param sysSite 站點實體* @return*/public static String getRedirectUrl(String hrefUrl, String metaTagsUrl, SysSite sysSite) {String redirectUrl = "";try {if (metaTagsUrl.startsWith("./") && SpiderUtils.isNode(hrefUrl, sysSite)) {if (hrefUrl.endsWith("/")) {redirectUrl = hrefUrl + metaTagsUrl.substring(2);} else {redirectUrl = hrefUrl + metaTagsUrl.substring(1);}} else if (metaTagsUrl.startsWith("./") && hrefUrl.endsWith(".html")) {hrefUrl = hrefUrl.substring(0, hrefUrl.lastIndexOf("/"));metaTagsUrl = metaTagsUrl.substring(1);redirectUrl = hrefUrl + metaTagsUrl;} else if ("../".equals(metaTagsUrl) && SpiderUtils.isNode(hrefUrl, sysSite)) {if (hrefUrl.endsWith("/")) {hrefUrl = hrefUrl.substring(0, hrefUrl.length() - 1);}redirectUrl = hrefUrl.substring(0, hrefUrl.lastIndexOf('/'));} else if ("/".equals(metaTagsUrl)) {redirectUrl = sysSite.getSiteDomain();} else {//SpiderUtils.saveLogText("需要獲取重定向以后的url--------------------hrefUrl:"+hrefUrl+"--------metaTagsUrl:"+metaTagsUrl);redirectUrl = JsoupHtmlUintUtils.getRedirectUrl(hrefUrl);//SpiderUtils.saveLogText("需要獲取重定向以后的url-----------返回結果---------redirectUrl:"+redirectUrl);}} catch (Exception e) {log.error("獲取的url失敗:" + e.getMessage(), e);}return redirectUrl;}/*** 獲取原標簽的url** @param refreshMeta* @return*/public static String getMetaTagsUrl(Element refreshMeta) {String refreshUrl = "";try {if (refreshMeta != null) {String patternString = "http-equiv\\s*=\\s*\"?Refresh\"?\\s*[\\s;]*content\\s*=\\s*\"?(\\d+);\\s*url\\s*=\\s*(\"?)(.*?)\\2\"";Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE);Matcher matcher = pattern.matcher(refreshMeta.html());if (matcher.find()) {refreshUrl = matcher.group(3);}}} catch (Exception e) {log.error("獲取元標簽的url失敗:" + e.getMessage(), e);}return refreshUrl;}/*** 獲取鏈接的狀態碼** @param url 爬蟲鏈接* @return*/public static Integer getUrlResponseCode(String url, Integer frequency) {int statusCode;try (HttpResponse response = HttpRequest.head(url).setConnectionTimeout(1000).execute()) {//使用hutool方法獲取狀態碼statusCode = response.getStatus();if (statusCode >= 400 && frequency < 3) {frequency = frequency + 1;try {Thread.sleep(200);} catch (InterruptedException e) {log.error("休眠異常:" + e.getMessage(), e);}statusCode = getUrlResponseCode(url, frequency);}} catch (Exception e) {log.error(url+"-----獲取url的狀態碼失敗:" + e.getMessage(), e);statusCode = 500;}return statusCode;}/*** 靜態爬蟲** @param url* @return*/private Document getStaticCrawlers(String url) {Document document = null;try {document = Jsoup.connect(url).timeout(5000).get();} catch (HttpStatusException e) {// 后臺異常處理if ((e.getStatusCode() + "").startsWith("5")) {try {Thread.sleep(2000); // 睡眠2秒document = Jsoup.connect(url).timeout(5000).get();} catch (IOException ex) {ex.getMessage();} catch (InterruptedException ex) {throw new RuntimeException(ex);}}} catch (Exception e) {e.printStackTrace();}return initUrl(url,document);}private Document getStaticCrawlers(String url, Integer waitTime) {Document document = null;try {document = Jsoup.connect(url).timeout(waitTime).get();} catch (HttpStatusException e) {// 后臺異常處理if ((e.getStatusCode() + "").startsWith("5")) {try {Thread.sleep(2000); // 睡眠2秒document = Jsoup.connect(url).timeout(waitTime).get();} catch (IOException ex) {ex.getMessage();} catch (InterruptedException ex) {throw new RuntimeException(ex);}}} catch (Exception e) {}return initUrl(url,document);}/*** 初始化Document中的相對路徑為絕對路徑* @param sourceUrl 基準URL,用于解析相對路徑* @param document Jsoup解析的Document對象* @return 處理后的Document* @throws IllegalArgumentException 如果基準URL無效*/public static Document initUrl(String sourceUrl, Document document) {try{if (ObjectUtils.isNotEmpty(document)){URI baseUri;try {baseUri = new URI(sourceUrl);} catch (URISyntaxException e) {throw new IllegalArgumentException("鏈接處理異常: " + sourceUrl, e);}Elements aList = document.select("a");for (Element element : aList) {String href = element.attr("href");// 跳過空或無效的href屬性if (href == null || href.isEmpty()) {continue;}//是javascript:void(0)類似這樣的非法鏈接if (SpiderUtils.filterJavaScript(href)) {continue;}//不符合url規則if (SpiderUtils.illegalUrl(href)) {continue;}try {URI resolvedUri = baseUri.resolve(href);element.attr("href", resolvedUri.toString());} catch (IllegalArgumentException e) {// 可選:記錄解析失敗的情況log.error("無法解析鏈接 '" + href + "': " + e.getMessage());}}}} catch (Exception e){log.info("document初始化鏈接異常:",e.getMessage(),e);}return document;}static class MyJSErrorListener extends DefaultJavaScriptErrorListener {@Overridepublic void scriptException(HtmlPage page, ScriptException scriptException) {}@Overridepublic void timeoutError(HtmlPage page, long allowedTime, long executionTime) {}@Overridepublic void malformedScriptURL(HtmlPage page, String url, MalformedURLException malformedURLException) {}@Overridepublic void loadScriptError(HtmlPage page, URL scriptUrl, Exception exception) {}@Overridepublic void warn(String message, String sourceName, int line, String lineSource, int lineOffset) {}}}