使用 xpath 进行 bash XHTML 解析
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4984689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
bash XHTML parsing using xpath
提问by Paused until further notice.
I'm writing a small script to learn how to parse an XHTML web page. The following command:
我正在编写一个小脚本来学习如何解析 XHTML 网页。以下命令:
cat q?s=goog.xhtml | xpath '//span[@id="yfs_l10_goog"]'
returns:
返回:
Found 2 nodes:
-- NODE --
<span id="yfs_l10_goog">624.50</span>-- NODE --
<span id="yfs_l10_goog">624.50</span>
How do I:
我如何能:
need to write my command in order to only extract the value
624.50
?what do I need to do to extract it only once ?
需要编写我的命令才能仅提取值
624.50
吗?我需要做什么才能只提取一次?
source page I'm parsing: http://finance.yahoo.com/q?s=goog
我正在解析的源页面:http: //finance.yahoo.com/q?s=goog
回答by Paused until further notice.
Edit 2:
编辑2:
Give this a try:
试试这个:
xpath -q -e '//span[@id="yfs_l10_goog"][1]/text()'
Edit:
编辑:
Pipe your output through:
通过管道输出您的输出:
sed -n '/span/{s/<span[^<]*>\([^<]*\)<.*//;p;q}'
Original answer:
原答案:
Using xmlstarlet
:
使用xmlstarlet
:
echo -e '<foo><span id="yfs_l10_goog">624.50</span>\n<bar>xyz</bar><span id="yfs_l10_goog">555.50</span>\n<span id="yfs_l10_goog">123.50</span></foo>' |
xmlstarlet sel -t -v "//span[@id='yfs_l10_goog']"
Result of query:
查询结果:
624.50
Result of echo
:
结果echo
:
<foo><span id="yfs_l10_goog">624.50</span>
<bar>xyz</bar><span id="yfs_l10_goog">555.50</span>
<span id="yfs_l10_goog">123.50</span></foo>
Result of xml fo
:
结果xml fo
:
<?xml version="1.0"?>
<foo>
<span id="yfs_l10_goog">624.50</span>
<bar>xyz</bar>
<span id="yfs_l10_goog">555.50</span>
<span id="yfs_l10_goog">123.50</span>
</foo>
Other queries:
其他查询:
$ echo -e '...' | xmlstarlet sel -t -v "//span[@id='yfs_l10_goog'][1]"
624.50
$ echo -e '...' | xmlstarlet sel -t -v "//span[@id='yfs_l10_goog'][3]"
123.50
$ echo -e '...' | xmlstarlet sel -t -v "//span[@id='yfs_l10_goog'][last()]"
123.50