brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: xmllint --html --xpath reads links out of messy HTML

Xml
~/tips/tip-xmllint-html-xpath-scrape

xmllint --html --xpath '//a/@href' page.html

Parses HTML with libxml2's forgiving HTML parser and prints whatever an XPath expression selects.

A regex for HTML always ends in tears. xmllint can parse HTML too, tolerates broken markup, and understands XPath, which makes it a decent quick scraper.

xmllint --html --xpath '//a/@href' page.html

The --html option switches to the HTML parser. Combined with --xpath you can pick out links, headings or anything else. A dash as file name reads from stdin, so it also works at the end of a pipe:

curl -s https://example.com/ | xmllint --html --xpath '//h1/text()' -

On libxml 2.9.14, a small page with two links printed one attribute per line, name included:

 href="/x"
 href="/y"

Wrap the path in string() or use text() at the end if you only want the value, as in '//main//a/text()'.

The caveat is noise. libxml2’s HTML parser does not know every HTML5 element: on that version a page with <nav> and <main> elements made it print HTML parser error : Tag nav invalid to stderr for each of them. The results were still correct and the exit status was 0, so 2>/dev/null is a reasonable fix:

xmllint --html --xpath '//a/@href' page.html 2>/dev/null

I’d only use this for quick jobs. Pages that build their content with JavaScript will not show it, because xmllint sees the HTML as it was sent, and a real scraper needs a proper library.

Further reading: xmllint man page

More Xml tips xmllint --xpath '//book/title/text()' feed.xml xmlstarlet ed -u '//item[@id="1"]/title' -v 'Changed' feed.xml xmlstarlet sel -t -v '//item/title' -n feed.xml All Xml tips (4) All topics

Link