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

如何抓取包含figure标签的mock-div类div内容?求正确XPath

解决XPath错误及正确提取写法

错误原因

你写的//figure~//是无效的XPath语法,~并不是XPath支持的运算符,这才导致抛出ValueError。

正确XPath写法

首先定位到符合要求的容器:所有包含figure标签、且class为mock-div的div,基础定位XPath为:

//div[@class='mock-div' and figure]

基于这个容器,分别提取你需要的内容:

  • 提取<h2>标签文本:
    //div[@class='mock-div' and figure]//h2/text()
    
    (如果h2是div的直接子节点,把//h2改成/h2更高效)
  • 提取<p>标签文本:
    //div[@class='mock-div' and figure]//p/text()
    
  • 提取<img>标签的src值:
    //div[@class='mock-div' and figure]//img/@src
    
  • 提取<img>标签的alt值:
    //div[@class='mock-div' and figure]//img/@alt
    
  • 提取<figcaption>标签文本:
    //div[@class='mock-div' and figure]//figcaption/text()
    

批量提取示例(Scrapy环境)

建议先定位目标容器再循环提取,避免重复遍历DOM:

target_divs = response.xpath("//div[@class='mock-div' and figure]")
for div in target_divs:
    h2_content = div.xpath(".//h2/text()").get(default="")
    p_content = div.xpath(".//p/text()").get(default="")
    img_src = div.xpath(".//img/@src").get(default="")
    img_alt = div.xpath(".//img/@alt").get(default="")
    figcap_content = div.xpath(".//figcaption/text()").get(default="")
    # 此处可添加数据存储或处理逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 17:38:26