首页 > 解决方案 > 使用 Xidel 提取同一行的 href 和 text,仅限特定链接

问题描述

我正在尝试为<a>html 页面中的多个链接提取标签内的链接(href)和文本。

我只想要特定的链接,我通过子字符串匹配。

我的html示例:

<a href="/this/dir/1234/">This should be 1234</a> some other html
<a href="/this/dir/1236/">This should be 1236</a> some other html
<a href="/about_us/">Not important link</a> some other html

我正在使用 Xidel,它可以让我避免使用正则表达式。这似乎是最简单的工作。

到目前为止我所拥有的:

xidel -e "//a/(@href[contains(.,'/this/dir')],text())"

它基本上可以工作,但仍然存在两个问题:

获得输出的推荐方法是什么

/this/dir/1234  ; This should be 1234
/this/dir/1236  ; This should be 1236

感谢任何反馈/提示。

编辑

Martin 提供的解决方案是 99%。没有输出换行符,所以我使用 awk 用换行符替换虚拟文本。

注意:我在窗户上。

xidel myhtml.htm -e "string-join(//a[contains(@href, '/this/dir')]!(@href || ' ; ' || .), 'XXX')" | awk -F "XXX" "{$1=$1}1" "OFS=\n" 

标签: xqueryxidel

解决方案


您可以将条件移动到谓词中,例如//a[contains(@href, '/this/dir')]!(@href, string())。至于结果格式,如果将所有内容委托给 XQuery 会发生什么

string-join(//a[contains(@href, '/this/dir')]!(@href || ' ; ' || .), '&#10;')

推荐阅读