Parsing HTML
suggest changeGo's standard library can generate HTML (see HTML templates), but it can't parse it. The parser lives in golang.org/x/net/html, a package maintained by the Go team outside the standard library:
go get golang.org/x/net/html
The package gives you two APIs:
html.Parsebuilds a tree of*html.Node, like the DOM in a browser. This is what you want most of the time.html.NewTokenizeris a low-level streaming tokenizer. It's faster and uses less memory, but it doesn't fix broken markup or build any structure for you.
The parser implements the HTML5 parsing algorithm, the same one browsers use. It never fails on bad HTML: unclosed tags, missing <html> or <body>, and misnested elements get repaired exactly the way a browser would repair them. Parse returns an error only when reading from the io.Reader fails.
Don't use regular expressions or encoding/xml for HTML. Real-world HTML isn't XML, and regular expressions can't handle nesting.
The node tree
html.Parse returns the root *html.Node, whose Type is html.DocumentNode. Every node has links to its parent, first and last child, and previous and next sibling, so you walk the tree with plain pointer chasing:
package main
import (
"fmt"
"log"
"strings"
"golang.org/x/net/html"
)
const page = `<title>My page</title>
<p>Hello <b>world
<p>Second paragraph`
func dump(n *html.Node, depth int) {
indent := strings.Repeat(" ", depth)
switch n.Type {
case html.DocumentNode:
fmt.Println(indent + "Document")
case html.ElementNode:
fmt.Printf("%sElement <%s>\n", indent, n.Data)
case html.TextNode:
fmt.Printf("%sText %q\n", indent, n.Data)
case html.CommentNode:
fmt.Printf("%sComment %q\n", indent, n.Data)
case html.DoctypeNode:
fmt.Printf("%sDoctype %s\n", indent, n.Data)
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
dump(c, depth+1)
}
}
func main() {
doc, err := html.Parse(strings.NewReader(page))
if err != nil {
log.Fatal(err)
}
dump(doc, 0)
}
Document
Element <html>
Element <head>
Element <title>
Text "My page"
Text "\n"
Element <body>
Element <p>
Text "Hello "
Element <b>
Text "world\n"
Element <p>
Element <b>
Text "Second paragraph"
The output shows how the parser repaired the input. It added the <html>, <head> and <body> elements, closed the first <p> when it saw the second one, and even re-opened the unclosed <b> inside the second paragraph, exactly like a browser.
The important fields of html.Node:
| Field | Meaning |
|---|---|
Type |
ElementNode, TextNode, DocumentNode, CommentNode, DoctypeNode or RawNode |
Data |
tag name for elements (always lowercase), text for text and comment nodes |
DataAtom |
tag name as an atom.Atom integer, 0 if the tag is unknown |
Attr |
slice of html.Attribute{Namespace, Key, Val}, keys are lowercase |
Parent, FirstChild, LastChild, PrevSibling, NextSibling |
tree links |
Text in Data and attribute values in Attr are already unescaped: & becomes &.
Iterating over nodes
In current versions of golang.org/x/net (v0.31.0 and later), Node has three methods that return iterators usable with for ... range:
n.Descendants()visits all nodes undernin depth-first order (document order), not includingn.n.ChildNodes()visits direct children ofn.n.Ancestors()visitsn.Parent, its parent and so on up to the document.
They remove the need to write recursive walk functions. Here's how to extract all links from a page and turn relative URLs into absolute ones with url.URL.Parse (see Parsing URLs):
package main
import (
"fmt"
"log"
"net/url"
"strings"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
const page = `<html><body>
<a href="/about">About</a>
<a href="docs/intro.html">Intro</a>
<a href="https://go.dev/">Go</a>
<a name="top">no href</a>
<A HREF="#faq">FAQ</A>
</body></html>`
// getAttr returns the value of attribute key and whether it was present.
func getAttr(n *html.Node, key string) (string, bool) {
for _, a := range n.Attr {
if a.Key == key {
return a.Val, true
}
}
return "", false
}
func main() {
doc, err := html.Parse(strings.NewReader(page))
if err != nil {
log.Fatal(err)
}
base, _ := url.Parse("https://example.com/blog/post.html")
for n := range doc.Descendants() {
if n.Type != html.ElementNode || n.DataAtom != atom.A {
continue
}
href, ok := getAttr(n, "href")
if !ok {
continue
}
u, err := base.Parse(href)
if err != nil {
continue
}
fmt.Printf("%-20s -> %s\n", href, u)
}
}
/about -> https://example.com/about
docs/intro.html -> https://example.com/blog/docs/intro.html
https://go.dev/ -> https://go.dev/
#faq -> https://example.com/blog/post.html#faq
Comparing n.DataAtom == atom.A is faster than n.Data == "a" because it compares integers. Package golang.org/x/net/html/atom has constants for all known HTML tag and attribute names. Notice that <A HREF=...> matched too: the parser lowercases tag and attribute names.
There is no GetAttribute method, so a small helper like getAttr above shows up in almost every program that uses this package.
Extracting text
The text of an element is spread across all TextNode descendants. To get it, concatenate them. You usually want to skip <script> and <style>, whose contents are also text nodes:
package main
import (
"fmt"
"log"
"strings"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
const page = `<html><head>
<title>Fish & Chips</title>
<style>body { color: red }</style>
<script>console.log("hi")</script>
</head><body>
<h1>Menu</h1>
<p>Cod and <em>chips</em>,
£9.50</p>
<!-- prices include VAT -->
</body></html>`
// textContent returns all text under n, skipping <script> and <style>.
func textContent(n *html.Node) string {
var sb strings.Builder
var walk func(*html.Node)
walk = func(n *html.Node) {
if n.Type == html.ElementNode &&
(n.DataAtom == atom.Script || n.DataAtom == atom.Style) {
return
}
if n.Type == html.TextNode {
sb.WriteString(n.Data)
}
for c := range n.ChildNodes() {
walk(c)
}
}
walk(n)
return sb.String()
}
func main() {
doc, err := html.Parse(strings.NewReader(page))
if err != nil {
log.Fatal(err)
}
for n := range doc.Descendants() {
if n.DataAtom == atom.Title {
fmt.Printf("title: %q\n", textContent(n))
}
}
body := textContent(doc)
fmt.Printf("raw: %q\n", body)
// Collapse runs of whitespace, like a browser does.
fmt.Printf("clean: %q\n", strings.Join(strings.Fields(body), " "))
}
title: "Fish & Chips"
raw: "\nFish & Chips\n\n\n\nMenu\nCod and chips,\n £9.50\n\n"
clean: "Fish & Chips Menu Cod and chips, £9.50"
A few things to notice:
- Entities like
&and£were decoded. - The comment is a
CommentNode, so it's not included. - Whitespace from the source is preserved.
strings.Fieldsplusstrings.Joinis a quick way to collapse it the way a browser displays it. - Here
textContentuses explicit recursion instead ofDescendants(), becauseDescendants()can't skip a whole subtree.
Finding elements by id and class
With Descendants() it's easy to write small findFirst and findAll helpers that take a predicate. The class attribute holds a space-separated list, so check it with strings.Fields rather than comparing the whole string:
package main
import (
"fmt"
"log"
"slices"
"strings"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
const page = `<html><body>
<div id="products">
<div class="product featured"><h2>Gopher plush</h2><span class="price">$25</span></div>
<div class="product"><h2>Go mug</h2><span class="price">$12</span></div>
<div class="product-list">not a product</div>
</div>
</body></html>`
func getAttr(n *html.Node, key string) string {
for _, a := range n.Attr {
if a.Key == key {
return a.Val
}
}
return ""
}
func hasClass(n *html.Node, class string) bool {
return slices.Contains(strings.Fields(getAttr(n, "class")), class)
}
// findFirst returns the first descendant of n for which match returns true.
func findFirst(n *html.Node, match func(*html.Node) bool) *html.Node {
for d := range n.Descendants() {
if match(d) {
return d
}
}
return nil
}
func findAll(n *html.Node, match func(*html.Node) bool) []*html.Node {
var res []*html.Node
for d := range n.Descendants() {
if match(d) {
res = append(res, d)
}
}
return res
}
func text(n *html.Node) string {
var sb strings.Builder
for d := range n.Descendants() {
if d.Type == html.TextNode {
sb.WriteString(d.Data)
}
}
return strings.TrimSpace(sb.String())
}
func byClass(class string) func(*html.Node) bool {
return func(n *html.Node) bool {
return n.Type == html.ElementNode && hasClass(n, class)
}
}
func main() {
doc, err := html.Parse(strings.NewReader(page))
if err != nil {
log.Fatal(err)
}
list := findFirst(doc, func(n *html.Node) bool {
return n.Type == html.ElementNode && getAttr(n, "id") == "products"
})
if list == nil {
log.Fatal("no #products")
}
for _, p := range findAll(list, byClass("product")) {
name := findFirst(p, func(n *html.Node) bool { return n.DataAtom == atom.H2 })
price := findFirst(p, byClass("price"))
fmt.Printf("%-14s %-5s featured=%v\n", text(name), text(price), hasClass(p, "featured"))
}
}
Gopher plush $25 featured=true
Go mug $12 featured=false
hasClass correctly rejects product-list, which a naive strings.Contains(class, "product") would accept.
If you write a lot of these queries, consider goquery, described later in this article.
Scraping a table
Tables are a common scraping target. Iterate over <tr> elements and collect the text of <td> and <th> children:
package main
import (
"fmt"
"log"
"strings"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
const page = `<table>
<tr><th>Language</th><th>Year</th></tr>
<tr><td>Go</td><td>2009</td></tr>
<tr><td>Rust</td><td>2010</td></tr>
<tr><td>Zig<td>2016
</table>`
func text(n *html.Node) string {
var sb strings.Builder
for d := range n.Descendants() {
if d.Type == html.TextNode {
sb.WriteString(d.Data)
}
}
return strings.TrimSpace(sb.String())
}
func main() {
doc, err := html.Parse(strings.NewReader(page))
if err != nil {
log.Fatal(err)
}
var rows [][]string
for n := range doc.Descendants() {
if n.DataAtom != atom.Tr {
continue
}
var row []string
for c := range n.ChildNodes() {
if c.DataAtom == atom.Td || c.DataAtom == atom.Th {
row = append(row, text(c))
}
}
rows = append(rows, row)
}
for _, r := range rows {
fmt.Printf("%q\n", r)
}
// The parser inserted the <tbody> that the source didn't have.
for n := range doc.Descendants() {
if n.DataAtom == atom.Tr {
var path []string
for a := range n.Ancestors() {
if a.Type == html.ElementNode {
path = append(path, a.Data)
}
}
fmt.Println("tr ancestors:", strings.Join(path, " < "))
break
}
}
}
["Language" "Year"]
["Go" "2009"]
["Rust" "2010"]
["Zig" "2016"]
tr ancestors: tbody < table < body < html
The last row in the source has no closing </td> tags, but the parser handles it. It also inserted a <tbody> that isn't in the source, because HTML5 requires one. Browsers do the same, which is why selectors copied from browser dev tools sometimes contain tbody. Code that walks a fixed path like table > tr would break on this, while searching descendants doesn't care.
Modifying the tree and rendering HTML
Nodes can be changed in place: edit Attr, and use AppendChild, InsertBefore and RemoveChild to restructure the tree. html.Render writes a tree back as HTML.
This example strips <script> elements and on* event attributes, adds rel="nofollow" to external links and appends a new element:
package main
import (
"log"
"os"
"slices"
"strings"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
const page = `<html><head><script src="track.js"></script></head>
<body><p onclick="evil()">Read <a href="https://go.dev">Go docs</a>
and <a href="/local">local page</a>.</p><script>alert(1)</script></body></html>`
func main() {
doc, err := html.Parse(strings.NewReader(page))
if err != nil {
log.Fatal(err)
}
// Collect first: changing the tree while iterating over it is not safe.
var scripts []*html.Node
for n := range doc.Descendants() {
if n.Type != html.ElementNode {
continue
}
switch n.DataAtom {
case atom.Script:
scripts = append(scripts, n)
case atom.A:
for _, a := range n.Attr {
if a.Key == "href" && strings.HasPrefix(a.Val, "http") {
n.Attr = append(n.Attr, html.Attribute{Key: "rel", Val: "nofollow"})
break
}
}
}
// Drop event handler attributes like onclick.
n.Attr = slices.DeleteFunc(n.Attr, func(a html.Attribute) bool {
return strings.HasPrefix(a.Key, "on")
})
}
for _, s := range scripts {
s.Parent.RemoveChild(s)
}
// Append a new element: <footer>Generated</footer> to <body>.
footer := &html.Node{Type: html.ElementNode, Data: "footer", DataAtom: atom.Footer}
footer.AppendChild(&html.Node{Type: html.TextNode, Data: "Generated <by Go>"})
body := doc.FirstChild.LastChild
body.AppendChild(footer)
if err := html.Render(os.Stdout, doc); err != nil {
log.Fatal(err)
}
}
<html><head></head>
<body><p>Read <a href="https://go.dev" rel="nofollow">Go docs</a>
and <a href="/local">local page</a>.</p><footer>Generated <by Go></footer></body></html>
Important rules:
- Don't add or remove nodes while iterating with
Descendants()orChildNodes(). Removing a node sets itsNextSiblingtonil, which ends the iteration early. Collect the nodes into a slice first, then change them. EditingAttrduring iteration is fine. AppendChildandInsertBeforepanic if the new node already has a parent or siblings. CallRemoveChildfirst to move a node.- When you create an element, set both
DataandDataAtom(useatom.Lookup([]byte(name))if you don't have a constant), because the renderer and other code may look at either. Renderescapes text, so<by Go>came out as<by Go>. Don't put raw HTML in aTextNode; parse it into nodes instead.doc.FirstChild.LastChildis<body>here only because the input has no doctype or leading comment. In real code, find<body>by searching foratom.Body.
Stripping scripts like this is not a complete HTML sanitizer. For untrusted HTML, such as user comments, use an allowlist-based sanitizer like bluemonday.
Parsing fragments
html.Parse always produces a complete document. When you have a snippet, for example from a CMS or an RSS feed, use html.ParseFragment. It takes a context element, which is the element the snippet would be placed in, because the parsing rules depend on it:
package main
import (
"fmt"
"log"
"strings"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
func main() {
// A snippet from a CMS, an RSS feed or a comment: not a full document.
snippet := `<li>One</li><li>Two <b>bold</li>`
context := &html.Node{Type: html.ElementNode, Data: "ul", DataAtom: atom.Ul}
nodes, err := html.ParseFragment(strings.NewReader(snippet), context)
if err != nil {
log.Fatal(err)
}
for _, n := range nodes {
var sb strings.Builder
html.Render(&sb, n)
fmt.Println(sb.String())
}
// Compare with Parse, which wraps everything in html/head/body.
doc, _ := html.Parse(strings.NewReader(snippet))
var sb strings.Builder
html.Render(&sb, doc)
fmt.Println(sb.String())
}
<li>One</li>
<li>Two <b>bold</b></li>
<html><head></head><body><li>One</li><li>Two <b>bold</b></li></body></html>
ParseFragment returns a slice of top-level nodes without the html, head and body wrappers. Passing nil as the context works like parsing inside <body>.
Streaming with the tokenizer
The tokenizer reads HTML token by token without building a tree. Use it for large documents or when you only need something simple, like all links or the title.
Call Next until it returns html.ErrorToken. Then z.Err() is io.EOF at the normal end of input:
package main
import (
"fmt"
"io"
"log"
"strings"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
const page = `<!DOCTYPE html>
<html><head><title>Streaming</title></head>
<body>
<a href="/one">One</a>
<img src="/logo.png" alt="logo"/>
<a href="/two" class="x">Two</a>
</body></html>`
func main() {
z := html.NewTokenizer(strings.NewReader(page))
inTitle := false
for {
tt := z.Next()
switch tt {
case html.ErrorToken:
if z.Err() == io.EOF {
return // normal end of input
}
log.Fatal(z.Err())
case html.StartTagToken, html.SelfClosingTagToken:
name, hasAttr := z.TagName()
a := atom.Lookup(name)
if a == atom.Title {
inTitle = true
}
for hasAttr {
var key, val []byte
key, val, hasAttr = z.TagAttr()
if (a == atom.A && string(key) == "href") ||
(a == atom.Img && string(key) == "src") {
fmt.Printf("%s %s=%s\n", name, key, val)
}
}
case html.EndTagToken:
name, _ := z.TagName()
if atom.Lookup(name) == atom.Title {
inTitle = false
}
case html.TextToken:
if inTitle {
fmt.Printf("title: %s\n", z.Text())
}
}
}
}
title: Streaming
a href=/one
img src=/logo.png
a href=/two
TagName, TagAttr and Text return byte slices that point into the tokenizer's internal buffer. They are only valid until the next call to Next, so convert to string (or copy) anything you want to keep. They are the fast path because they don't allocate.
For convenience, z.Token() returns an html.Token struct with Type, Data and Attr as owned strings:
package main
import (
"fmt"
"io"
"strings"
"golang.org/x/net/html"
)
const page = `<p class=intro>Hi <img src=a.png alt="A & B"><br/>bye`
func main() {
z := html.NewTokenizer(strings.NewReader(page))
for {
tt := z.Next()
if tt == html.ErrorToken {
fmt.Println("end:", z.Err() == io.EOF)
return
}
t := z.Token()
fmt.Printf("%-16v %-6q %v\n", tt, t.Data, t.Attr)
}
}
StartTag "p" [{ class intro}]
Text "Hi " []
StartTag "img" [{ src a.png} { alt A & B}]
SelfClosingTag "br" []
Text "bye" []
end: true
The tokenizer doesn't fix anything. The <p> is never closed, <img> is reported as a StartTag because it wasn't written as <img/>, and nothing tracks which element contains which. If you need that, use html.Parse.
CSS selectors with goquery
Hand-written tree walks get verbose. goquery wraps golang.org/x/net/html with a jQuery-like API and CSS selectors:
go get github.com/PuerkitoBio/goquery
package main
import (
"fmt"
"log"
"strings"
"github.com/PuerkitoBio/goquery"
)
const page = `<html><head><title>Shop</title></head><body>
<ul id="products">
<li class="product featured" data-sku="G1"><h2>Gopher plush</h2><span class="price">$25</span></li>
<li class="product" data-sku="M2"><h2>Go mug</h2><span class="price">$12</span></li>
</ul>
<nav><a href="/page/2">Next</a> <a href="https://go.dev">Go</a></nav>
</body></html>`
func main() {
doc, err := goquery.NewDocumentFromReader(strings.NewReader(page))
if err != nil {
log.Fatal(err)
}
fmt.Println("title:", doc.Find("title").Text())
doc.Find("#products li.product").Each(func(i int, s *goquery.Selection) {
sku, _ := s.Attr("data-sku")
name := s.Find("h2").Text()
price := s.Find(".price").Text()
fmt.Printf("%d %s %-13s %s featured=%v\n", i, sku, name, price, s.HasClass("featured"))
})
// Attribute selectors work too.
for _, s := range doc.Find(`a[href^="http"]`).EachIter() {
fmt.Println("external:", s.AttrOr("href", ""))
}
html, _ := doc.Find("li.featured").Html()
fmt.Println("inner html:", html)
fmt.Println("count:", doc.Find("li").Length())
}
title: Shop
0 G1 Gopher plush $25 featured=true
1 M2 Go mug $12 featured=false
external: https://go.dev
inner html: <h2>Gopher plush</h2><span class="price">$25</span>
count: 2
Findtakes any CSS selector supported by cascadia: tags,#id,.class, attribute selectors,:nth-child, combinators and more.- A
*goquery.Selectionholds zero or more nodes. Methods likeTextandFindoperate on all of them, whileAttrandHtmluse the first one. Eachcalls a function for every node.EachIterreturns an iterator for use withfor ... range.Selection.Nodesgives access to the underlying[]*html.Node, andgoquery.NewDocumentFromNodewraps a tree you've already parsed.
Fetching and parsing a web page
When parsing a page downloaded with the HTTP client, check the status code and the content type, and remember that the parser expects UTF-8. Pages in other encodings, such as windows-1252 or Shift JIS, must be converted first. Package golang.org/x/net/html/charset detects the encoding from the Content-Type header, a byte order mark or a <meta> tag, and returns a reader that produces UTF-8:
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
"golang.org/x/net/html/charset"
)
// fetchTitle downloads url and returns the text of its <title>.
func fetchTitle(url string) (string, error) {
resp, err := http.Get(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("GET %s: %s", url, resp.Status)
}
ct := resp.Header.Get("Content-Type")
if !strings.HasPrefix(ct, "text/html") {
return "", fmt.Errorf("GET %s: not HTML: %s", url, ct)
}
// Convert from the page's encoding (header, BOM or <meta>) to UTF-8.
r, err := charset.NewReader(resp.Body, ct)
if err != nil {
return "", err
}
doc, err := html.Parse(r)
if err != nil {
return "", err
}
for n := range doc.Descendants() {
if n.DataAtom == atom.Title && n.FirstChild != nil {
return n.FirstChild.Data, nil
}
}
return "", nil
}
func main() {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/utf8":
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprint(w, "<title>Zażółć gęślą jaźń</title>")
case "/latin1":
// "Café" in windows-1252: é is the single byte 0xE9.
w.Header().Set("Content-Type", "text/html")
w.Write([]byte("<meta charset=\"windows-1252\"><title>Caf\xe9</title>"))
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
for _, p := range []string{"/utf8", "/latin1", "/missing"} {
title, err := fetchTitle(srv.URL + p)
if err != nil {
fmt.Println("error:", strings.Replace(err.Error(), srv.URL, "", 1))
continue
}
fmt.Printf("%-8s %q\n", p, title)
}
}
/utf8 "Zażółć gęślą jaźń"
/latin1 "Café"
error: GET /missing: 404 Not Found
Without charset.NewReader the second title would contain the invalid UTF-8 byte 0xE9 instead of é.
When scraping real sites, also set a timeout on the client, set a descriptive User-Agent (see Set User-Agent), respect robots.txt and don't hammer the server with parallel requests.
Escaping and unescaping
If you only need to escape or decode entities, you don't need a parser. The standard library package html has two functions:
package main
import (
"fmt"
"html"
)
func main() {
s := `<a href="x">Tom & "Jerry"</a>`
esc := html.EscapeString(s)
fmt.Println(esc)
fmt.Println(html.UnescapeString(esc))
fmt.Println(html.UnescapeString("© 2026 — café 😀 €"))
}
<a href="x">Tom & "Jerry"</a>
<a href="x">Tom & "Jerry"</a>
© 2026 — café 😀 €
html.EscapeString escapes only <, >, &, ' and ". html.UnescapeString handles all named entities from the HTML5 spec as well as numeric ones. The same functions also exist in golang.org/x/net/html.
Summary
- Use
golang.org/x/net/html.html.Parsebuilds a tree and repairs broken HTML like a browser. It returns an error only on I/O failure. - Walk the tree with
Descendants(),ChildNodes()andAncestors(). Compare tags withDataAtomand write a smallgetAttrhelper. - Text is spread across
TextNodechildren. Skip<script>and<style>, and collapse whitespace withstrings.Fields. - Check classes with
strings.Fields, not substring matching. - Collect nodes before removing or moving them, then write the result with
html.Render. - Use
ParseFragmentfor snippets andNewTokenizerfor fast streaming. Copy tokenizer byte slices you want to keep. - Use goquery for CSS selectors.
- Convert non-UTF-8 pages with
charset.NewReaderbefore parsing.