You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Jsoup提取Jakmall商品价格与重量失败,寻求技术支持

解决Jsoup提取Jakmall商品价格和重量的问题

嘿,我帮你捋捋问题出在哪,以及怎么搞定这个提取需求~

首先看你写的代码,getElementsByAttributeValue("class", "div[dp__price dp__price--2 format__money]")这行明显用错了:这个方法是用来匹配class属性的完整字符串值,但你写的是CSS选择器的格式,还多了错误的div[前缀,这肯定找不到目标元素。

先修正静态爬取的选择器写法

Jsoup最方便的是用select()方法来写CSS选择器,针对这个商品的价格元素,正确的写法应该是这样:

Document doc = Jsoup.connect("https://www.jakmall.com/tokocamzone/mi-travel-charger-20a-output-fast-charging#9730928979371").get();
// 匹配同时拥有dp__price、dp__price--2、format__money这三个类的元素
Elements priceElements = doc.select(".dp__price.dp__price--2.format__money");
if (!priceElements.isEmpty()) {
    String price = priceElements.first().text().trim();
    System.out.println("商品价格:" + price);
} else {
    System.out.println("没找到价格元素,可能是页面动态加载的问题");
}

如果还是拿不到数据?大概率是动态加载的锅

Jakmall很多商品数据是通过JavaScript动态渲染的,Jsoup只能抓取服务器返回的静态HTML,没法执行页面的JS代码。这时候就得换用支持JS渲染的工具,比如Selenium(需要搭配对应浏览器的Driver,比如ChromeDriver):

// 初始化ChromeDriver,记得提前下载对应版本的驱动并配置路径
WebDriver driver = new ChromeDriver();
driver.get("https://www.jakmall.com/tokocamzone/mi-travel-charger-20a-output-fast-charging#9730928979371");
// 等待元素加载完成,避免因为页面没渲染完就抓取
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

// 提取价格
WebElement priceElement = wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(".dp__price.dp__price--2.format__money")));
String price = priceElement.getText().trim();
System.out.println("商品价格:" + price);

// 提取重量:先定位规格区域里的重量项
WebElement weightElement = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[contains(text(), 'Weight')]/following-sibling::*")));
String weight = weightElement.getText().trim();
System.out.println("商品重量:" + weight);

// 用完记得关闭浏览器
driver.quit();

关于提取重量的补充思路

如果页面规格是静态HTML,用Jsoup也能直接抓:先找到规格模块的容器,再遍历每一项找重量对应的行:

Elements specRows = doc.select(".product-spec .spec-row");
for (Element row : specRows) {
    String label = row.select(".spec-label").text().trim();
    // 忽略大小写匹配"Weight"
    if (label.equalsIgnoreCase("Weight")) {
        String weight = row.select(".spec-value").text().trim();
        System.out.println("商品重量:" + weight);
        break;
    }
}

内容的提问来源于stack exchange,提问作者Hamzah Nursaufa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:48:59