cheerio for Go
github.com/malcolmston/cheerio
HTML parsing and jQuery-style traversal for Go.
GitHubports cheeriojs/cheerio
A dependency-free, standard-library-only Go take on the Node.js cheerio package: tolerant HTML parsing plus a chainable, jQuery-style traversal API. Everything is built from scratch — its own HTML tokenizer and tree-construction parser, a CSS selector engine, and the Selection API — with no cgo and no third-party code, not even golang.org/x/net. Load never fails: malformed markup is recovered the way a browser would into a *Node tree, then Find returns an ordered, de-duplicated Selection you can filter, traverse, read and lightly mutate. The import path is github.com/malcolmston/cheerio and the package is named cheerio.
Install
shell
$ go get github.com/malcolmston/cheerioQuick start
main.go
import "github.com/malcolmston/cheerio"
doc := cheerio.Load(`
<ul id="fruit">
<li class="a">Apple</li>
<li class="b">Banana</li>
</ul>
<a href="/go">Go</a>`)
// Text of the first list item.
fmt.Println(doc.Find("#fruit li").First().Text()) // Apple
// Iterate over matched elements.
doc.Find("li").Each(func(i int, n *cheerio.Node) {
fmt.Println(i, n.Children[0].Data)
})
// Attribute access plus a pseudo-class.
href, _ := doc.Find("a").Attr("href")
fmt.Println(href, doc.Find("li:nth-child(odd)").Length()) // /go 1Features
- Tolerant parsing —
Loadrecovers malformed HTML into a*Nodetree (DocumentNode/ElementNode/TextNode/CommentNode/DoctypeNode) using its own tokenizer + tree builder, nogolang.org/x/net - CSS selector engine — type/
*/#id/.class, attribute matches ([a^=v],[a$=v],[a*=v],[a~=v],[a|=v]), combinators>+~, and pseudo-classes:nth-child(an+b)/:not - Chainable traversal —
Find,Children,Parent,Parents,Closest,Siblings,Next/Prev,Filter,Not,Is,Has,Eq,First/Last,Each,Map - Accessors —
Attr/AttrOr,Text,Html(inner),OuterHtml,HasClass,Val,TagName - Light mutation —
SetAttr,RemoveAttr,AddClass,RemoveClass,ToggleClass,SetText - Browser-like recovery — void elements take no children, self-closing syntax is honored, implicit-close rules fire for
<p>/<li>/<tr>, raw-text<script>/<style>/<textarea>capture verbatim, and named/decimal/hex character references are decoded - Deterministic — identical input yields identical output and Selections preserve document order;
Valresolves<input>/<select>/<textarea>values - Zero dependencies — pure Go standard library, no cgo, nothing to audit but the toolchain