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

使用Xpath提取ah_sec_product_price类内容失败,求正确写法

解决XPath匹配class错误的问题

问题原因

你使用的contains(@class, "ah_sec_product_price")会匹配所有class属性值中包含该字符串的div,而ah_sec_product_price_del的class恰好包含ah_sec_product_price子串,所以返回了错误的元素。

正确的XPath写法

有两种可靠方式可精准匹配目标class:

  1. 精确匹配单一class
    如果目标div的class只有ah_sec_product_price,直接用精确匹配:
//div[@class="ah_sec_product_price"]
  1. 兼容多class场景
    如果目标div可能同时存在多个class(比如<div class="ah_sec_product_price other-class">),用拼接空格的方式确保匹配独立类名:
//div[contains(concat(" ", @class, " "), " ah_sec_product_price ")]

这种方式会给class属性值前后添加空格,再匹配带空格的目标类名,彻底避免子串误匹配的问题。

PHP代码示例

// 使用兼容多class的XPath查询目标元素
$product_prices = $xpath_object->query('//div[contains(concat(" ", @class, " "), " ah_sec_product_price ")]');

// 检查匹配结果并输出内容
if ($product_prices->length > 0) {
    $price_text = trim($product_prices->item(0)->nodeValue);
    echo $price_text; // 输出:۲۸,۴۰۶ تومان
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 16:35:21