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


儀表我們大多數人都使用愛並使用 jq 命令。 它適用於 Linux 或類 Unix 系統,並從 JSON 文檔中提取數據。最近發現的 htmlq 和 jq 一樣,都是用 Rust 語言編寫的。 想像一下能夠 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 上的源代碼試一試,讓我們知道您在下面的評論部分中喜歡什麼。