在一次XPath调用中仅选择属性

前端开发 2026-07-08
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]/p[5]/span/span/math'

输出

'





          sin

            2


        ⁡
        θ
        +

          cos

            2


        ⁡
        θ
        =
        1
        ,


    {\displaystyle \sin ^{2}\theta +\cos ^{2}\theta =1,}

这真是一团糟,因为它并没有只输出 alttext 属性的内容,而

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]/p[5]/span/span/math' --output-format=xml | xidel -e 'math/semantics/annotation'

输出

{\displaystyle \sin ^{2}\theta +\cos ^{2}\theta =1,}

,虽然这是正确的字符串,但命令太冗长。

真的没法用一个XPath查询来完成吗?

更新

我忽略了提取属性的语法其实只是 /@<attribute>,所以答案是:

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]/p[5]/span/span/math/@alttext'

在尝试提取属性时,有一点要记住:[@alttext]@alttext 是不同的,这一点也被这个答案证明了:https://stackoverflow.com/a/79958424/22133250

xidel 版本在示例中使用

$ xidel --version
Xidel 0.9.9
Compiled with FPC3.2.2 aarch64-Linux R+S+Q+

https://www.videlibri.de/xidel.html
by Benito van der Zander <benito AT benibela.de>

解决方案

工作代码使用 /@<attribute,而不是 /[@<attribute>] 语法:

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]/p[5]/span/span/math/@alttext'

这是因为前者是 Abbreviated Syntax for an attribute,而后者是 Filter Expression

This W3Schools page illustrates the difference:

//@lang Selects all attributes that are named lang

...

//title[@lang] Selects all the title elements that have an attribute named lang

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章