Java Web Scraping实战 使用Jsoup和Selenium结合XPath高效解析网页数据解决数据抓取难题

引言:Web Scraping在现代数据获取中的重要性
Web Scraping(网络爬虫)已经成为现代数据驱动决策中不可或缺的技术。在当今信息爆炸的时代,大量有价值的数据分布在各种网站上,而Web Scraping技术能够帮助我们自动化地从这些网站中提取所需信息。对于Java开发者而言,掌握高效的Web Scraping技术不仅能够解决数据获取难题,还能在数据分析、竞品监控、价格追踪等多个场景中发挥重要作用。
本文将深入探讨如何使用Java结合Jsoup和Selenium这两种强大的工具,并结合XPath技术来高效解析网页数据。我们将从基础概念讲起,逐步深入到实际应用中的高级技巧,帮助读者构建稳定、高效的Web Scraping解决方案。
Web Scraping基础概念与技术选型
什么是Web Scraping?
Web Scraping是一种从网页中提取结构化数据的技术。与传统的API数据获取方式相比,Web Scraping能够获取那些没有提供API接口的网站数据,或者在API限制较多时提供替代方案。
为什么选择Java进行Web Scraping?
Java作为企业级应用开发的主流语言,具有以下优势:
稳定性
:Java虚拟机提供了稳定的运行环境
丰富的生态系统
:拥有大量成熟的第三方库
多线程支持
:便于构建并发爬虫系统
企业级集成
:易于与现有Java系统集成
Jsoup与Selenium的技术对比
特性
Jsoup
Selenium
执行环境
纯Java,无需浏览器
需要浏览器驱动
速度
极快
相对较慢
JavaScript支持
不支持
完全支持
内存占用
极低
较高
适用场景
静态页面、简单动态页面
复杂动态页面、SPA应用
反爬虫对抗
较弱
较强(模拟真实用户)
XPath在数据解析中的作用
XPath(XML Path Language)是一种在XML和HTML文档中查找信息的语言。它提供了比CSS选择器更强大的定位能力,特别是在处理复杂嵌套结构时表现出色。
Jsoup基础使用详解
Jsoup简介与环境配置
Jsoup是一个纯Java的HTML解析库,它提供了方便的API来提取和操作HTML数据。首先,我们需要在项目中添加Jsoup依赖:


org.jsoup
jsoup
1.17.2

Jsoup基本使用示例
让我们通过一个完整的例子来学习Jsoup的基础用法:
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class JsoupBasicExample {
public static void main(String[] args) {
try {
// 1. 从URL直接解析
Document doc = Jsoup.connect(“https://example.com”)
.userAgent(“Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36”)
.timeout(5000)
.get();

// 2. 获取页面标题
String title = doc.title();
System.out.println(“页面标题: ” + title);

// 3. 使用CSS选择器提取元素
Elements links = doc.select(“a[href]”); // 所有带href属性的链接
for (Element link : links) {
String text = link.text();
String url = link.attr(“abs:href”); // 获取绝对URL
System.out.println(“链接文本: ” + text + “, URL: ” + url);
}

// 4. 提取特定元素内容
Elements paragraphs = doc.select(“p”);
for (Element p : paragraphs) {
System.out.println(“段落内容: ” + p.text());
}

// 5. 获取元素属性
Element logo = doc.selectFirst(“#logo”);
if (logo != null) {
String logoSrc = logo.attr(“src”);
System.out.println(“Logo图片地址: ” + logoSrc);
}

} catch (Exception e) {
e.printStackTrace();
}
}
}
Jsoup高级选择器技巧
Jsoup支持复杂的CSS选择器,这对于精确提取数据至关重要:
public class JsoupAdvancedSelector {
public void demonstrateSelectors() {
Document doc = Jsoup.parse(“…“);

// 1. 后代选择器
Elements items = doc.select(“div.container > ul li”);

// 2. 属性选择器
Elements inputs = doc.select(“input[type=’text’][name=’username’]”);

// 3. 伪类选择器
Elements firstChild = doc.select(“div > p:first-child”);
Elements lastChild = doc.select(“div > p:last-child”);
Elements nthChild = doc.select(“div > p:nth-child(2)”);

// 4. 组合选择器
Elements results = doc.select(“div.product, div.item, div.goods”);

// 5. 通配符选择器
Elements allElements = doc.select(“*”);

// 6. 兄弟选择器
Elements nextSiblings = doc.select(“h2 + p”); // 紧接在h2后的p元素
Elements allSiblings = doc.select(“h2 ~ p”); // h2后的所有p兄弟元素
}
}
Jsoup处理复杂HTML结构
在实际项目中,我们经常需要处理复杂的HTML结构。以下是一个完整的商品信息提取示例:
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class ProductInfoExtractor {

// 模拟的HTML内容
private static final String HTML_CONTENT = “””

iPhone 15 Pro

¥7999

Apple
手机

4.8
1250条评价


“””;

public void extractProductInfo() {
Document doc = Jsoup.parse(HTML_CONTENT);

// 提取所有商品信息
Elements products = doc.select(“.product-item”);

for (Element product : products) {
// 提取商品ID
String productId = product.attr(“data-id”);

// 提取商品标题
String title = product.selectFirst(“.product-title”).text();

// 提取价格并清理格式
String priceText = product.selectFirst(“.product-price”).text();
double price = Double.parseDouble(priceText.replace(“¥”, “”).trim());

// 提取品牌和分类
String brand = product.selectFirst(“.brand”).text();
String category = product.selectFirst(“.category”).text();

// 提取评分信息
Element ratings = product.selectFirst(“.ratings”);
double score = Double.parseDouble(ratings.selectFirst(“.score”).text());
String reviewCount = ratings.selectFirst(“.count”).text();

// 提取按钮信息
String buyButtonOnclick = product.selectFirst(“.btn-buy”).attr(“onclick”);
String cartButtonData = product.selectFirst(“.btn-add-cart”).attr(“data-product”);

// 输出提取结果
System.out.println(“=== 商品信息 ===”);
System.out.println(“ID: ” + productId);
System.out.println(“标题: ” + title);
System.out.println(“价格: ¥” + price);
System.out.println(“品牌: ” + brand);
System.out.println(“分类: ” + category);
System.out.println(“评分: ” + score + ” (” + reviewCount + “)”);
System.out.println(“购买按钮: ” + buyButtonOnclick);
System.out.println(“购物车按钮数据: ” + cartButtonData);
System.out.println();
}
}

public static void main(String[] args) {
new ProductInfoExtractor().extractProductInfo();
}
}
Selenium基础与高级应用
Selenium环境配置与驱动管理
Selenium需要浏览器驱动才能工作。以下是ChromeDriver的配置示例:


org.seleniumhq.selenium
selenium-java
4.18.1

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;

import java.time.Duration;
import java.util.List;

public class SeleniumSetup {

public WebDriver setupDriver() {
// 设置ChromeDriver路径(如果不在PATH中)
// System.setProperty(“webdriver.chrome.driver”, “path/to/chromedriver”);

// 配置Chrome选项
ChromeOptions options = new ChromeOptions();
options.addArguments(“–headless”); // 无头模式
options.addArguments(“–disable-gpu”);
options.addArguments(“–no-sandbox”);
options.addArguments(“–disable-dev-shm-usage”);
options.addArguments(“–user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36”);

// 创建WebDriver实例
WebDriver driver = new ChromeDriver(options);

// 设置隐式等待
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

return driver;
}
}
Selenium基本操作示例
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import java.util.List;

public class SeleniumBasicOperations {

public void performBasicOperations(WebDriver driver) {
try {
// 1. 访问网页
driver.get(“https://example.com”);

// 2. 元素定位与交互
// 通过ID定位
WebElement usernameInput = driver.findElement(By.id(“username”));
usernameInput.sendKeys(“testuser”);

// 通过CSS选择器定位
WebElement passwordInput = driver.findElement(By.cssSelector(“input[type=’password’]”));
passwordInput.sendKeys(“password123”);

// 通过XPath定位
WebElement loginButton = driver.findElement(By.xpath(“//button[@type=’submit’]”));
loginButton.click();

// 3. 等待元素出现(显式等待)
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement resultElement = wait.until(
ExpectedConditions.presenceOfElementLocated(By.className(“result”))
);

// 4. 获取元素信息
String text = resultElement.getText();
String className = resultElement.getAttribute(“class”);
boolean isDisplayed = resultElement.isDisplayed();

System.out.println(“结果文本: ” + text);
System.out.println(“CSS类名: ” + className);
System.out.println(“是否可见: ” + isDisplayed);

// 5. 处理多个元素
List links = driver.findElements(By.tagName(“a”));
for (WebElement link : links) {
System.out.println(“链接文本: ” + link.getText());
System.out.println(“链接地址: ” + link.getAttribute(“href”));
}

// 6. JavaScript执行
JavascriptExecutor js = (JavascriptExecutor) driver;
String pageTitle = (String) js.executeScript(“return document.title”);
System.out.println(“页面标题: ” + pageTitle);

// 7. 滚动页面
js.executeScript(“window.scrollTo(0, document.body.scrollHeight)”);

} catch (Exception e) {
e.printStackTrace();
}
}
}
Selenium处理动态内容与AJAX
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
import java.time.Duration;

public class DynamicContentHandler {

public void handleDynamicContent(WebDriver driver) {
driver.get(“https://dynamic-website.com”);

// 1. 等待AJAX请求完成
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(15));

// 等待特定元素出现
WebElement dynamicElement = wait.until(
ExpectedConditions.presenceOfElementLocated(By.id(“dynamic-content”))
);

// 2. 等待元素可见
WebElement visibleElement = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.className(“loaded-content”))
);

// 3. 等待元素可点击
WebElement clickableButton = wait.until(
ExpectedConditions.elementToBeClickable(By.id(“load-more”))
);
clickableButton.click();

// 4. 等待多个条件
wait.until(ExpectedConditions.and(
ExpectedConditions.presenceOfElementLocated(By.id(“content-1”)),
ExpectedConditions.presenceOfElementLocated(By.id(“content-2”))
));

// 5. 处理无限滚动
JavascriptExecutor js = (JavascriptExecutor) driver;

// 滚动到底部直到没有新内容
long lastHeight = (long) js.executeScript(“return document.body.scrollHeight”);
while (true) {
js.executeScript(“window.scrollTo(0, document.body.scrollHeight)”);
Thread.sleep(2000); // 等待新内容加载

long newHeight = (long) js.executeScript(“return document.body.scrollHeight”);
if (newHeight == lastHeight) {
break; // 没有新内容加载
}
lastHeight = newHeight;
}

// 6. 处理iframe
driver.switchTo().frame(“iframe-name”);
// 在iframe内操作
WebElement iframeContent = driver.findElement(By.tagName(“body”));
System.out.println(“iframe内容: ” + iframeContent.getText());
driver.switchTo().defaultContent(); // 切换回主文档

// 7. 处理新窗口/标签页
String originalWindow = driver.getWindowHandle();
driver.findElement(By.linkText(“在新窗口打开”)).click();

// 等待新窗口打开
wait.until(ExpectedConditions.numberOfWindowsToBe(2));

// 切换到新窗口
for (String windowHandle : driver.getWindowHandles()) {
if (!windowHandle.equals(originalWindow)) {
driver.switchTo().window(windowHandle);
break;
}
}

System.out.println(“新窗口标题: ” + driver.getTitle());

// 切换回原窗口
driver.switchTo().window(originalWindow);
}
}
XPath在Java中的应用
XPath基础语法
XPath是一种在XML和HTML文档中导航和查询的语言。在Java中,我们可以使用XPath来精确定位元素。
import javax.xml.xpath.*;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import java.io.StringReader;

public class XPathBasics {

public void demonstrateXPath() {
// XPath基本表达式
String[] xpaths = {
“/html/body/div”, // 绝对路径
“//div”, // 相对路径(所有div)
“//div[@class=’product’]”, // 带属性的元素
“//div[@class=’product’]/h3”, // 子元素
“//div[contains(@class, ‘product’)]”, // 包含属性值
“//div[@id=’main’]/a[1]”, // 第一个子元素
“//div[last()]”, // 最后一个元素
“//div[position() <= 3]", // 前三个元素 "//*[text()='立即购买']", // 文本匹配 "//button[contains(text(), '购买')]", // 包含文本 "//div[@class='product' and @data-price > 1000]”, // 组合条件
“//div[not(@class=’hidden’)]”, // 取反条件
“//div[@class=’product’]/following-sibling::div”, // 兄弟元素
“//div[@class=’product’]/parent::div”, // 父元素
“//div[@class=’product’]//a”, // 任意深度后代
“//*[@id and @class]” // 同时具有id和class属性
};

for (String xpath : xpaths) {
System.out.println(“XPath: ” + xpath);
}
}
}
在Jsoup中使用XPath
虽然Jsoup原生不支持XPath,但我们可以通过第三方库或转换为CSS选择器来实现类似功能:
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

public class JsoupXPathAdapter {

// 将简单XPath转换为CSS选择器
public String xpathToCss(String xpath) {
// 简单的XPath到CSS转换规则
xpath = xpath.replace(“//”, ” “); // 相对路径转换
xpath = xpath.replace(“/”, ” > “); // 子元素转换
xpath = xpath.replaceAll(“@(\\w+)”, “$1”); // 属性转换
xpath = xpath.replaceAll(“\\[(\\d+)\\]”, “:nth-of-type($1)”); // 索引转换
xpath = xpath.replaceAll(“\\[@(\\w+)='([^’]+)\\]”, “[$1=’$2′]”); // 属性值匹配
xpath = xpath.replaceAll(“contains\\(@(\\w+), ‘([^’]+)\\)”, “[$1*=’$2′]”); // contains转换

return xpath.trim();
}

public void extractWithXPathLike() {
Document doc = Jsoup.parse(“…“);

// 示例://div[@class=’product’]/h3
String cssSelector = xpathToCss(“//div[@class=’product’]/h3”);
Elements products = doc.select(cssSelector);

// 更复杂的例子://div[@class=’product’ and @data-price > 1000]/h3
// 在Jsoup中需要分步处理
Elements allProducts = doc.select(“div.product”);
for (Element product : allProducts) {
String priceStr = product.attr(“data-price”);
if (!priceStr.isEmpty()) {
double price = Double.parseDouble(priceStr);
if (price > 1000) {
Element title = product.selectFirst(“h3”);
System.out.println(“高价商品: ” + title.text());
}
}
}
}
}
在Selenium中使用XPath
Selenium原生支持XPath,这是其强大功能之一:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
import java.time.Duration;
import java.util.List;

public class SeleniumXPathOperations {

public void performXPathOperations(WebDriver driver) {
// 1. 基本XPath定位
WebElement element1 = driver.findElement(By.xpath(“//div[@class=’product’]”));

// 2. 使用文本定位
WebElement buyButton = driver.findElement(By.xpath(“//button[text()=’立即购买’]”));

// 3. 使用contains函数
WebElement searchInput = driver.findElement(By.xpath(“//input[contains(@placeholder, ‘搜索’)]”));

// 4. 使用逻辑运算符
WebElement product = driver.findElement(By.xpath(“//div[@class=’product’ and @data-active=’true’]”));

// 5. 使用索引
WebElement firstProduct = driver.findElement(By.xpath(“//div[@class=’product’][1]”));

// 6. 使用轴(Axes)
WebElement parent = driver.findElement(By.xpath(“//div[@class=’product’]/..”));
WebElement nextSibling = driver.findElement(By.xpath(“//div[@class=’product’]/following-sibling::div[1]”));
WebElement previousSibling = driver.findElement(By.xpath(“//div[@class=’product’]/preceding-sibling::div[1]”));

// 7. 使用多个条件
WebElement complexElement = driver.findElement(By.xpath(
“//div[contains(@class, ‘item’) and @data-price > 100 and not(contains(@class, ‘hidden’))]”
));

// 8. 查找多个元素
List products = driver.findElements(By.xpath(“//div[@class=’product’]”));

// 9. 等待XPath元素出现
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement dynamicElement = wait.until(
ExpectedConditions.presenceOfElementLocated(By.xpath(“//div[@class=’loaded’]”))
);

// 10. 使用XPath轴处理复杂结构
// 查找所有商品的名称(兄弟关系)
List productNames = driver.findElements(By.xpath(
“//div[@class=’product-item’]/div[@class=’info’]/h3”
));

// 查找特定商品的下一个价格标签
WebElement specificPrice = driver.findElement(By.xpath(
“//div[@class=’product-item’ and @data-id=’1001′]/following-sibling::div[@class=’price-tag’][1]”
));
}

// 高级XPath技巧
public void advancedXPath(WebDriver driver) {
// 1. 使用变量和参数化
String productId = “1001”;
WebElement product = driver.findElement(By.xpath(
“//div[@data-id=’” + productId + “‘]”
));

// 2. 动态构建XPath
String[] attributes = {“class”, “data-category”, “data-brand”};
StringBuilder xpath = new StringBuilder(“//div[“);
for (int i = 0; i < attributes.length; i++) { if (i > 0) xpath.append(” and “);
xpath.append(“@”).append(attributes[i]).append(“=’value’”);
}
xpath.append(“]”);

WebElement dynamicElement = driver.findElement(By.xpath(xpath.toString()));

// 3. 使用XPath函数处理文本
// 包含特定文本的元素
WebElement textElement = driver.findElement(By.xpath(“//*[contains(text(), ‘重要信息’)]”));

// 以特定文本开头
WebElement startsWithElement = driver.findElement(By.xpath(“//*[starts-with(text(), ‘开始’)]”));

// 文本精确匹配(忽略空格)
WebElement normalizeElement = driver.findElement(By.xpath(
“//*[normalize-space(text())=’精确文本’]”
));
}
}
Jsoup与Selenium结合使用策略
何时使用Jsoup,何时使用Selenium
使用Jsoup的场景:
静态HTML页面
需要快速处理大量页面
内存和CPU资源受限
简单的数据提取任务
使用Selenium的场景:
需要执行JavaScript才能显示内容
SPA(单页应用)或复杂的AJAX交互
需要模拟用户交互(点击、输入、滚动)
需要绕过反爬虫机制
结合使用策略
在实际项目中,我们通常结合使用两者:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

public class CombinedScrapingStrategy {

public void scrapeWithBothTools(String url) {
// 1. 使用Selenium获取动态渲染后的HTML
WebDriver driver = new ChromeDriver();
try {
driver.get(url);

// 等待动态内容加载
Thread.sleep(3000);

// 2. 获取页面源代码
String html = driver.getPageSource();

// 3. 使用Jsoup解析HTML(更快、更高效)
Document doc = Jsoup.parse(html);

// 4. 使用Jsoup提取数据
String title = doc.selectFirst(“h1”).text();
String price = doc.selectFirst(“.price”).text();

System.out.println(“标题: ” + title);
System.out.println(“价格: ” + price);

} catch (Exception e) {
e.printStackTrace();
} finally {
driver.quit();
}
}
}
完整的实战项目:电商网站数据抓取
下面是一个完整的电商网站数据抓取系统,结合了Jsoup、Selenium和XPath:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

public class EcommerceScraper {

private WebDriver driver;
private WebDriverWait wait;
private JavascriptExecutor js;

public EcommerceScraper(WebDriver driver) {
this.driver = driver;
this.wait = new WebDriverWait(driver, Duration.ofSeconds(15));
this.js = (JavascriptExecutor) driver;
}

// 商品数据模型
public static class Product {
String id;
String name;
double price;
String brand;
String category;
double rating;
int reviewCount;
String imageUrl;
String detailUrl;

@Override
public String toString() {
return String.format(“商品[ID=%s, 名称=%s, 价格=%.2f, 品牌=%s, 分类=%s, 评分=%.1f, 评价数=%d]”,
id, name, price, brand, category, rating, reviewCount);
}
}

/**
* 抓取商品列表页面
*/
public List scrapeProductList(String listUrl) {
List products = new ArrayList<>();

try {
// 1. 访问商品列表页
driver.get(listUrl);

// 2. 等待商品容器加载
wait.until(ExpectedConditions.presenceOfElementLocated(
By.xpath(“//div[contains(@class, ‘product-list’)]”)
));

// 3. 滚动页面加载所有商品
scrollPageToLoadAll();

// 4. 获取页面源代码并用Jsoup解析
String html = driver.getPageSource();
Document doc = Jsoup.parse(html);

// 5. 使用XPath-like选择器提取商品项
Elements productElements = doc.select(“div.product-item”);

for (Element productEl : productElements) {
Product product = extractProductInfo(productEl);
if (product != null) {
products.add(product);
}
}

} catch (Exception e) {
System.err.println(“抓取商品列表失败: ” + e.getMessage());
e.printStackTrace();
}

return products;
}

/**
* 滚动页面直到所有商品加载完成
*/
private void scrollPageToLoadAll() {
long lastHeight = (long) js.executeScript(“return document.body.scrollHeight”);
int unchangedCount = 0;

while (unchangedCount < 3) { // 连续3次高度不变认为加载完成 js.executeScript("window.scrollTo(0, document.body.scrollHeight)"); Thread.sleep(2000); // 等待加载 long newHeight = (long) js.executeScript("return document.body.scrollHeight"); if (newHeight == lastHeight) { unchangedCount++; } else { unchangedCount = 0; lastHeight = newHeight; } } } /** * 从商品元素中提取详细信息 */ private Product extractProductInfo(Element productEl) { try { Product product = new Product(); // 提取商品ID(从data属性) product.id = productEl.attr("data-product-id"); // 提取商品名称 Element nameEl = productEl.selectFirst(".product-name, h3, .title"); product.name = nameEl != null ? nameEl.text() : "未知"; // 提取价格(清理格式) Element priceEl = productEl.selectFirst(".price, .current-price"); if (priceEl != null) { String priceText = priceEl.text().replaceAll("[^0-9.]", ""); product.price = priceText.isEmpty() ? 0 : Double.parseDouble(priceText); } // 提取品牌 Element brandEl = productEl.selectFirst(".brand, [data-brand]"); product.brand = brandEl != null ? brandEl.text() : "未知"; // 提取分类 Element categoryEl = productEl.selectFirst(".category, .breadcrumb"); product.category = categoryEl != null ? categoryEl.text() : "未知"; // 提取评分和评价数 Element ratingEl = productEl.selectFirst(".rating, .score"); if (ratingEl != null) { String ratingText = ratingEl.text(); try { product.rating = Double.parseDouble(ratingText); } catch (NumberFormatException e) { product.rating = 0; } } Element reviewEl = productEl.selectFirst(".review-count, .reviews"); if (reviewEl != null) { String reviewText = reviewEl.text().replaceAll("[^0-9]", ""); product.reviewCount = reviewText.isEmpty() ? 0 : Integer.parseInt(reviewText); } // 提取图片URL Element imgEl = productEl.selectFirst("img"); if (imgEl != null) { product.imageUrl = imgEl.attr("abs:src"); } // 提取详情页URL Element linkEl = productEl.selectFirst("a"); if (linkEl != null) { product.detailUrl = linkEl.attr("abs:href"); } return product; } catch (Exception e) { System.err.println("提取商品信息失败: " + e.getMessage()); return null; } } /** * 抓取商品详情页(使用Selenium处理动态内容) */ public Product scrapeProductDetail(String detailUrl) { try { // 1. 访问详情页 driver.get(detailUrl); // 2. 等待关键信息加载 wait.until(ExpectedConditions.presenceOfElementLocated( By.xpath("//div[contains(@class, 'product-detail')]") )); // 3. 使用Selenium提取动态内容 Product product = new Product(); // 提取商品ID(从URL或页面数据) product.id = extractProductIdFromUrl(detailUrl); // 提取名称(可能需要等待) WebElement nameElement = wait.until(ExpectedConditions.presenceOfElementLocated( By.xpath("//h1[@class='product-title']") )); product.name = nameElement.getText(); // 提取价格(可能需要等待价格加载) WebElement priceElement = wait.until(ExpectedConditions.presenceOfElementLocated( By.xpath("//span[contains(@class, 'price')]") )); String priceText = priceElement.getText().replaceAll("[^0-9.]", ""); product.price = Double.parseDouble(priceText); // 提取品牌(使用XPath) List brandElements = driver.findElements(By.xpath(
“//div[@class=’brand-info’]//span[@class=’brand-name’]”
));
product.brand = brandElements.isEmpty() ? “未知” : brandElements.get(0).getText();

// 提取分类(使用XPath轴)
WebElement categoryElement = driver.findElement(By.xpath(
“//div[@class=’breadcrumb’]//span[last()]”
));
product.category = categoryElement.getText();

// 提取评分(可能需要等待评分组件加载)
try {
WebElement ratingElement = wait.until(ExpectedConditions.presenceOfElementLocated(
By.xpath(“//div[@class=’rating-summary’]//span[@class=’score’]”)
));
product.rating = Double.parseDouble(ratingElement.getText());
} catch (Exception e) {
product.rating = 0;
}

// 提取评价数
try {
WebElement reviewElement = driver.findElement(By.xpath(
“//div[@class=’rating-summary’]//span[@class=’count’]”
));
String reviewText = reviewElement.getText().replaceAll(“[^0-9]”, “”);
product.reviewCount = Integer.parseInt(reviewText);
} catch (Exception e) {
product.reviewCount = 0;
}

// 提取图片URL
WebElement imageElement = driver.findElement(By.xpath(
“//div[@class=’product-images’]//img”
));
product.imageUrl = imageElement.getAttribute(“src”);

product.detailUrl = detailUrl;

return product;

} catch (Exception e) {
System.err.println(“抓取详情页失败: ” + e.getMessage());
e.printStackTrace();
return null;
}
}

/**
* 从URL中提取商品ID
*/
private String extractProductIdFromUrl(String url) {
// 假设URL格式: https://example.com/product/12345
String[] parts = url.split(“/”);
return parts[parts.length – 1];
}

/**
* 主抓取方法:结合列表页和详情页
*/
public List fullScrape(String listUrl, boolean includeDetails) {
List products = scrapeProductList(listUrl);

if (includeDetails) {
for (int i = 0; i < products.size(); i++) { Product product = products.get(i); if (product.detailUrl != null) { Product detailedProduct = scrapeProductDetail(product.detailUrl); if (detailedProduct != null) { // 合并信息 product.price = detailedProduct.price; product.rating = detailedProduct.rating; product.reviewCount = detailedProduct.reviewCount; product.imageUrl = detailedProduct.imageUrl; } } // 进度显示 System.out.printf("进度: %d/%d%n", i + 1, products.size()); } } return products; } public void close() { if (driver != null) { driver.quit(); } } } 使用示例 public class MainApplication { public static void main(String[] args) { // 配置WebDriver ChromeOptions options = new ChromeOptions(); options.addArguments("--headless"); options.addArguments("--disable-gpu"); options.addArguments("--no-sandbox"); WebDriver driver = new ChromeDriver(options); EcommerceScraper scraper = new EcommerceScraper(driver); try { // 执行完整抓取 List products = scraper.fullScrape(
“https://example.com/products”,
true
);

// 输出结果
System.out.println(“=== 抓取结果 ===”);
for (EcommerceScraper.Product product : products) {
System.out.println(product);
}

// 保存到文件(示例)
saveToFile(products, “products.json”);

} catch (Exception e) {
e.printStackTrace();
} finally {
scraper.close();
}
}

private static void saveToFile(List products, String filename) {
// 实现保存逻辑
System.out.println(“保存 ” + products.size() + ” 个商品到 ” + filename);
}
}
反爬虫策略与应对方案
常见反爬虫机制
User-Agent检测
IP频率限制
验证码
JavaScript混淆
动态Token
浏览器指纹
应对策略代码实现
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.util.Random;

public class AntiScrapingHandler {

/**
* 配置反检测的浏览器选项
*/
public ChromeOptions getStealthOptions() {
ChromeOptions options = new ChromeOptions();

// 基础反检测
options.addArguments(“–disable-blink-features=AutomationControlled”);
options.addArguments(“–disable-infobars”);
options.addArguments(“–start-maximized”);

// 隐藏自动化特征
options.setExperimentalOption(“excludeSwitches”, new String[]{“enable-automation”});
options.setExperimentalOption(“useAutomationExtension”, false);

// 随机User-Agent
options.addArguments(“–user-agent=” + getRandomUserAgent());

// 其他反检测参数
options.addArguments(“–disable-dev-shm-usage”);
options.addArguments(“–disable-accelerated-2d-canvas”);
options.addArguments(“–no-first-run”);
options.addArguments(“–no-zygote”);
options.addArguments(“–disable-gpu”);

return options;
}

/**
* 随机User-Agent生成器
*/
private String getRandomUserAgent() {
String[] userAgents = {
“Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36”,
“Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36”,
“Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36”,
“Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:121.0) Gecko/20100101 Firefox/121.0”
};

Random random = new Random();
return userAgents[random.nextInt(userAgents.length)];
}

/**
* 随机延迟
*/
public void randomDelay(int minSeconds, int maxSeconds) {
try {
Random random = new Random();
int delay = minSeconds + random.nextInt(maxSeconds – minSeconds + 1);
Thread.sleep(delay * 1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}

/**
* 模拟人类操作模式
*/
public void humanLikeInteraction(WebDriver driver, String cssSelector) {
// 随机移动鼠标(通过JavaScript)
JavascriptExecutor js = (JavascriptExecutor) driver;

// 随机滚动
int scrollTimes = new Random().nextInt(3) + 1;
for (int i = 0; i < scrollTimes; i++) { int scrollAmount = new Random().nextInt(500) + 100; js.executeScript("window.scrollBy(0, " + scrollAmount + ")"); randomDelay(1, 2); } // 随机等待后点击 randomDelay(2, 5); // 实际点击操作... } } 性能优化与最佳实践 1. 并发抓取优化 import java.util.concurrent.*; import java.util.List; import java.util.ArrayList; public class ConcurrentScraper { private final ExecutorService executor; private final int threadCount; public ConcurrentScraper(int threadCount) { this.threadCount = threadCount; this.executor = Executors.newFixedThreadPool(threadCount); } public List scrapeConcurrently(List urls) {
List> futures = new ArrayList<>();
List results = new ArrayList<>();

// 提交任务
for (String url : urls) {
Future future = executor.submit(() -> {
// 每个线程创建自己的WebDriver实例
WebDriver driver = createDriver();
try {
EcommerceScraper scraper = new EcommerceScraper(driver);
return scraper.scrapeProductDetail(url);
} finally {
driver.quit();
}
});
futures.add(future);
}

// 收集结果
for (Future future : futures) {
try {
Product product = future.get(30, TimeUnit.SECONDS);
if (product != null) {
results.add(product);
}
} catch (Exception e) {
System.err.println(“任务执行失败: ” + e.getMessage());
}
}

return results;
}

private WebDriver createDriver() {
ChromeOptions options = new ChromeOptions();
options.addArguments(“–headless”);
return new ChromeDriver(options);
}

public void shutdown() {
executor.shutdown();
}
}
2. 内存优化
public class MemoryOptimizedScraper {

/**
* 使用流式处理避免内存溢出
*/
public void scrapeLargeSite(String baseUrl) {
int page = 1;
boolean hasMore = true;

while (hasMore && page <= 100) { // 设置上限 String url = baseUrl + "?page=" + page; // 抓取单页 List pageProducts = scrapePage(url);

if (pageProducts.isEmpty()) {
hasMore = false;
} else {
// 处理并立即保存,避免累积
saveProducts(pageProducts);
pageProducts.clear(); // 立即释放内存
}

page++;

// 定期强制GC
if (page % 10 == 0) {
System.gc();
}
}
}

private List scrapePage(String url) {
// 实现单页抓取逻辑
return new ArrayList<>();
}

private void saveProducts(List products) {
// 实现保存逻辑
}
}
3. 错误处理与重试机制
public class RetryableScraper {

private static final int MAX_RETRIES = 3;
private static final int BASE_DELAY = 2; // 秒

public Product scrapeWithRetry(String url) {
int attempt = 0;
Exception lastException = null;

while (attempt < MAX_RETRIES) { try { return attemptScrape(url); } catch (Exception e) { lastException = e; attempt++; if (attempt < MAX_RETRIES) { // 指数退避 int delay = BASE_DELAY * (int) Math.pow(2, attempt - 1); System.out.println("尝试失败," + delay + "秒后重试..."); try { Thread.sleep(delay * 1000); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); break; } } } } System.err.println("所有重试失败: " + lastException.getMessage()); return null; } private Product attemptScrape(String url) throws Exception { // 实际的抓取逻辑 return new Product(); } } 数据存储与处理 1. 保存到JSON文件 import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; import java.util.List; public class JsonStorage { private final ObjectMapper mapper; public JsonStorage() { this.mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); } public void saveProducts(List products, String filename) {
try {
mapper.writeValue(new File(filename), products);
System.out.println(“保存成功: ” + filename);
} catch (Exception e) {
System.err.println(“保存失败: ” + e.getMessage());
}
}

public List loadProducts(String filename) throws Exception {
return mapper.readValue(new File(filename),
mapper.getTypeFactory().constructCollectionType(List.class, Product.class));
}
}
2. 保存到数据库
import java.sql.*;
import java.util.List;

public class DatabaseStorage {

private Connection connection;

public DatabaseStorage(String dbUrl, String user, String password) throws SQLException {
this.connection = DriverManager.getConnection(dbUrl, user, password);
createTableIfNotExists();
}

private void createTableIfNotExists() throws SQLException {
String sql = “””
CREATE TABLE IF NOT EXISTS products (
id VARCHAR(50) PRIMARY KEY,
name VARCHAR(255),
price DECIMAL(10,2),
brand VARCHAR(100),
category VARCHAR(100),
rating DECIMAL(3,1),
review_count INT,
image_url VARCHAR(500),
detail_url VARCHAR(500),
scraped_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
“””;

try (Statement stmt = connection.createStatement()) {
stmt.execute(sql);
}
}

public void saveProduct(Product product) throws SQLException {
String sql = “””
INSERT INTO products (id, name, price, brand, category, rating, review_count, image_url, detail_url)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
name = VALUES(name),
price = VALUES(price),
brand = VALUES(brand),
category = VALUES(category),
rating = VALUES(rating),
review_count = VALUES(review_count),
image_url = VALUES(image_url),
detail_url = VALUES(detail_url)
“””;

try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
pstmt.setString(1, product.id);
pstmt.setString(2, product.name);
pstmt.setDouble(3, product.price);
pstmt.setString(4, product.brand);
pstmt.setString(5, product.category);
pstmt.setDouble(6, product.rating);
pstmt.setInt(7, product.reviewCount);
pstmt.setString(8, product.imageUrl);
pstmt.setString(9, product.detailUrl);

pstmt.executeUpdate();
}
}

public void saveProducts(List products) throws SQLException {
connection.setAutoCommit(false);

for (Product product : products) {
saveProduct(product);
}

connection.commit();
connection.setAutoCommit(true);
}
}
法律与道德考虑
1. 遵守robots.txt
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.net.URL;

public class RobotsTxtChecker {

public boolean isAllowed(String url, String userAgent) {
try {
URL urlObj = new URL(url);
String robotsUrl = urlObj.getProtocol() + “://” + urlObj.getHost() + “/robots.txt”;

Document doc = Jsoup.connect(robotsUrl)
.userAgent(userAgent)
.timeout(5000)
.get();

String robotsContent = doc.body().text();

// 简单的robots.txt解析(实际应使用专门库)
return !robotsContent.contains(“Disallow: ” + urlObj.getPath());

} catch (Exception e) {
// 如果robots.txt不存在,默认允许
return true;
}
}
}
2. 请求频率控制
public class RateLimiter {

private final long minInterval; // 毫秒
private long lastRequestTime = 0;

public RateLimiter(int requestsPerMinute) {
this.minInterval = 60000L / requestsPerMinute;
}

public synchronized void acquire() throws InterruptedException {
long now = System.currentTimeMillis();
long waitTime = minInterval – (now – lastRequestTime);

if (waitTime > 0) {
Thread.sleep(waitTime);
}

lastRequestTime = System.currentTimeMillis();
}
}
总结
本文详细介绍了使用Java进行Web Scraping的完整技术栈,包括:
Jsoup基础与高级应用
:从简单的HTML解析到复杂的商品信息提取
Selenium核心功能
:处理动态内容、AJAX请求、用户交互
XPath技术
:在Java中高效定位和提取数据
结合策略
:何时使用哪种工具,如何组合使用
实战项目
:完整的电商网站数据抓取系统
反爬虫应对
:各种反检测技术
性能优化
:并发、内存、错误处理
数据存储
:JSON和数据库存储方案
法律道德
:合规性考虑
通过掌握这些技术,开发者可以构建稳定、高效、合规的Web Scraping系统,解决各种数据获取难题。记住,技术是中性的,关键在于如何负责任地使用它。