我們大多數人使用 love 並使用 jq 命令。 它適用於 Linux 或類 Unix 系統,並從 JSON 文檔中提取數據。我最近發現了像jq這樣用Rust語言寫的htmlq。 想像一下能夠 sed 或 grep HTML 數據。 您可以使用 htmlq 來搜索、切片和過濾 HTML 數據。安裝並使用這個方便的工具,了解如何在 Linux 或 Unix 上處理 HTML 數據。

什麼是htmlq工具?

像 jq 但用於 HTML。 使用 CSS 選擇器提取部分 HTML 文件。 CSS 使用選擇器在網頁上定位 HTML 元素以設置樣式。例如,您可以使用此工具輕鬆提取圖像和其他 URL。

在 Linux 或 Unix 上安裝 htmlq

以下是如何使用 apt/apt-get 命令在 Ubuntu 或 Debian Linux 上安裝 Cargo 和 rustc。
sudo apt install cargo

然後運行:
cargo install htmlq

macOS 安裝貨物

打開終端應用程序並運行端口命令,如下所示:
sudo port install cargo

或者,您可以在 macOS 上安裝 Homebrew 並使用 brew 包管理器,如下所示:

brew install rustup # installs both cargo and rustc
rustup-init
rustc --version

FreeBSD安裝貨

使用 pkg 命令安裝 rustc,如下所示:
sudo pkg install rust

了解如何安裝 Rust 其他操作系統現在您已經有了 rustc 和 cargo 工具,輸入以下簡單命令以在您的開發系統上獲取 htmlq。
cargo install htmlq

設置你的路徑

確保添加 $HOME/.cargo/bin 路徑變量 能夠使用導出命令運行已安裝的二進製文件

# sh/bash/ksh etc
 PATH="$PATH:$HOME/.cargo/bin" 
 
# tcsh/csh etc
setenv PATH $PATH:$HOME/.cargo/bin

如何在 Linux 或 Unix 上使用 htmlq 從 HTML 文件中提取內容

讓我們使用 curl 命令按 ID 查找頁面部分。
curl -s url | htmlq '#css-selector'
curl -s url2 | htmlq '#css-selector'
curl -s https://www.cyberciti.biz/faq/ | htmlq --pretty '#content' | more

htmlq 輸出

找到頁面中的所有鏈接。例如:

curl -s https://www.nixcraft.com | htmlq --attribute href a

得到幫助

趕緊跑:
htmlq --help

htmlq 0.0.1
Michael Maclean <[email protected]>
Runs CSS selectors on HTML
 
USAGE:
    htmlq [FLAGS] [OPTIONS] <selector>...
 
FLAGS:
    -h, --help                 Prints help information
    -w, --ignore-whitespace    When printing text nodes, ignore those that consist entirely of whitespace
    -p, --pretty               Pretty-print the serialised output
    -t, --text                 Output only the contents of text nodes inside selected elements
    -V, --version              Prints version information
 
OPTIONS:
    -a, --attribute <attribute>    Only return this attribute (if present) from selected elements
    -f, --filename <FILE>          The input file. Defaults to stdin
    -o, --output <FILE>            The output file. Defaults to stdout
 
ARGS:
    <selector>...    The CSS expression to select

加上

htmlq 是一個非常好的工具,我喜歡它。做 查看Github上的源代碼試一試,讓我們知道您在下面的評論部分喜歡什麼。