從 html 檔案中取得選定的標籤

從 html 檔案中取得選定的標籤

我有一個頁面來源,我需要從此文件中獲取所有標籤。順序很重要。我需要外部腳本和內聯腳本。標籤必須包含在輸出中。我正在尋找一個控制台 Linux 工具。

我嘗試搜索,但找不到任何內容,因此我使用 jQuery 來獲取此資訊並將其貼到文件中。但這個輸出有一些奇怪的編碼,所以我需要傳統地解析它。

範例: 輸入:

<html>
  <head>
    <script src="script1.js"></script>
    <script src="script2.js"></script>
    <script>alert('hello');</script>
  </head>
  <body>
    <div id="main">...</div>
    <script src="footer.js">
  </body>
</html>

輸出:

<script src="script1.js"></script>
<script src="script2.js"></script>
<script>alert('hello');</script>
<script src="footer.js">

第二個範例,僅輸出 src 屬性。

script1.js
script2.js
inline script 
footer.js

答案1

您可以使用grep它及其唯一匹配參數 ( -o),例如:

$ grep -o "<[^>]*>" <(curl -s http://example.com/)

這將列印所有 html 標籤,包括訂單。

若要僅包含<script>標籤,請嘗試(更改index.html您的文件):

$ grep -Eo "<script.*(</script>|>)" index.html

為了僅獲取檔案名稱(從src屬性),您可以透過新增另一個來擴展grep,例如:

$ grep -Eo "<script.*(</script>|>)" index.html | grep -o '"[^"]*"' | tr -d '"'

上述語法無法幫助您處理 html 程式碼的許多不同變體,因此對於更複雜的解決方案,使用正規表示式解析html通常不建議這樣做,因此您應該使用適當的工具(您喜歡的語言或查看這些外殼工具)。

答案2

我知道您已經接受了答案,但我還想補充一點,您可以查看路徑

它專門用於 xml 樣式資料。

在你的情況下,xpath 是

//script

這裡也是另一個有人使用 xpath 解析 HTML 的例子

相關內容