簡體   English   中英

使用 sed 或 grep 提取 HTML 標簽之間的文本

[英]Extract Text between HTML tags with sed or grep

我有個問題。 我想使用 sed 或 grep 命令獲取此 html 的兩個部分的值。 我如何提取它們?

測試.html:

<html>
 <body>
  <div id="foo" class="foo">
   Some Text.
    <p id="author" class="author">
     <br>
     <a href="example.com">bar</a>
    </p>
  </div>
 </body>
</html>

腳本.sh

#!/bin/bash

author=$(sed 's/.*<p id="author" class="author"><br><a href="*">\(.*\)<\/a><\/p>.*/\1/p' test.html)
quote=$(sed 's/.*<div id="foo" class="foo">\(.*\)<\/div>.*/\1/p' test.html)

在線下我只想要值中的文本。 沒有html標簽。 但是我的腳本確實有效..

代碼:

text="$(sed 's:^ *::g' < test.html | tr -d \\n)"
author=$(sed 's:.*<p id="author" class="author"><br><a href="[^"]*">\([^<]*\)<.*:\1:' <<<"$text")
quote=$(sed 's:.*<div id="foo" class="foo">\([^<]*\)<.*:\1:' <<<"$text")
echo "'$author' '$quote'"

怎么運行的:

  1. $text被分配了一個未縮進的單行表示test.html 請注意, :用作sed的定界符而不是/ ,因為任何字符都可以作為定界符,並且我們正在解析的文本存在/ -s,因此我們不必使用\ -s 來轉義它們構建正則表達式。
  2. $author假定在<p id="author" class="author"><br><a href="[^"]*"> (其中[^"]*表示 «除"之外的任何字符,重復N 次,N ∈ [0, +∞)») 和接下來出現的任何標簽。
  3. $quote假定在<div id="foo" class="foo">和接下來的任何標簽之間。
  4. 相當晦澀的構造<<<"$text"就是所謂的here-string ,它幾乎等同於echo "$text" | 放在開頭。

你可以使用html2text

# cat test.html | html2text
Some Text.


[bar](example.com)

我經常使用 curl

# curl -s http://www.example.com/ | html2text

# Example Domain

This domain is for use in illustrative examples in documents. You may use this
domain in literature without prior coordination or asking for permission.

[More information...](https://www.iana.org/domains/example)

#

您可以使用xmllint來解析 html/xml 文本並為定義的 xpath 提取值。

這是工作示例:

#!/bin/bash

author=$(xmllint --html --xpath '//div[@class="foo"]/text()' test.html | tr -d '\n' | sed -e "s/ //g")
quote=$(xmllint --html --xpath '//a/text()' test.html | sed -e "s/ //g")
echo "Author:'$author'"
echo "Quote:'$quote'"
  • xpath定義需要從中提取文本的 xml 節點路徑。
  • tr用於刪除換行符。
  • sed用於從提取的文本值中修剪字符串。

不要使用正則表達式來解析 HTML/XML ,而是使用像這樣的專用解析器:

$ xidel -s test.html -e '//p/a,//div/normalize-space(text())'
bar
Some Text.
$ eval $(xidel test.html -se 'author:=//p/a,quote:=//div/normalize-space(text())' --output-format=bash)

$ printf '%s\n' "$author" "$quote"
bar
Some Text.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM