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

为何Xidel提取XML格式img元素后二次查询返回空输出?

Xidel管道处理XML无输出的原因分析

问题场景

执行以下命令能正常输出目标<img>元素的XML:

xidel 'https://en.wikipedia.org/wiki/List_of_trigonometric_identities' -e '/html/body/div[3]/div/div[3]/main/div[3]/div[3]/div[2]/table[1]/tbody/tr[2]/td/span/a/img' --output-format=xml

输出结果:

<?xml version="1.0" encoding="UTF-8"?>
<img src="//upload.wikimedia.org/wikipedia/commons/thumb/4/48/Trig_Functions.svg/250px-Trig_Functions.svg.png" decoding="async" width="250" height="250" class="mw-file-element" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/4/48/Trig_Functions.svg/500px-Trig_Functions.svg.png 2x" data-file-width="419" data-file-height="419"/>

但使用管道传递给第二个Xidel命令时,结果为空:

xidel 'https://en.wikipedia.org/wiki/List_of_trigonometric_identities' -e '/html/body/div[3]/div/div[3]/main/div[3]/div[3]/div[2]/table[1]/tbody/tr[2]/td/span/a/img' --output-format=xml | xidel -e '*[@src]'

原因解析

1. XPath表达式逻辑错误

第二个Xidel中的*[@src]表达式,含义是匹配当前上下文节点的所有子元素中带有src属性的节点。但第一个命令输出的XML根节点就是<img>元素,它是自闭合标签,没有任何子元素,因此无法匹配到内容。

2. 输入解析模式不匹配

Xidel默认以HTML模式解析输入内容,而第一个命令输出的是带XML声明的标准XML。HTML解析器会自动为裸元素包裹<html><body>结构,此时XML会被解析成:

<html>
  <body>
    <img src="..." .../>
  </body>
</html>

这时*[@src]会从根节点<html>开始查找子元素,<html>的子元素是<body>,没有src属性,自然返回空。

解决方法

需要同时修正XPath表达式,并指定第二个Xidel以XML模式解析输入:

# 直接提取img的src属性
xidel 'https://en.wikipedia.org/wiki/List_of_trigonometric_identities' -e '/html/body/div[3]/div/div[3]/main/div[3]/div[3]/div[2]/table[1]/tbody/tr[2]/td/span/a/img' --output-format=xml | xidel --input-format=xml -e '/img/@src'

或者用更通用的表达式匹配所有src属性:

xidel 'https://en.wikipedia.org/wiki/List_of_trigonometric_identities' -e '/html/body/div[3]/div/div[3]/main/div[3]/div[3]/div[2]/table[1]/tbody/tr[2]/td/span/a/img' --output-format=xml | xidel --input-format=xml -e './/@src'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 17:07:06