ZetCode

Go parse HTML with net/html

last modified October 30, 2026 Go 1.27

In this article we show how to parse HTML in Go with the golang.org/x/net/html package. It offers two APIs: a tokenizer that reports tags and text as a stream, and a tree parser that builds a complete document and lets us search it.

The tokenizer returns a TokenType and some data for every token: the tag name for start and end tags, the content for text, comments and doctypes. html.Parse reads an io.Reader and returns the root *html.Node of a tree in which every element, text, comment and doctype is a node.

All examples in this article were compiled and run with Go 1.27.0 and golang.org/x/net v0.62.0.

Installing the package

The package is not part of the standard library. It lives in the x/net module, which also contains the HTTP/2 implementation used by net/http.

$ go mod init example.com/nethtml
$ go get golang.org/x/net
go: added golang.org/x/net v0.62.0

The parser follows the WHATWG HTML5 algorithm, so it accepts the same markup a browser accepts, including documents that are not well formed.

The demo documents

The examples read three small files. The first one is a list of colours with an id on one item and a footer.

index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Colours</title>
</head>
<body>

<p>
    A list of colours
</p>

<ul>
    <li>red</li>
    <li>green</li>
    <li>blue</li>
    <li id="yellow">yellow</li>
    <li>orange</li>
    <li>brown</li>
    <li>pink</li>
</ul>

<footer>
    A footer
</footer>

</body>
</html>

The second file contains two links and a paragraph with escapes, and the third one is deliberately broken: some tags are never closed.

links.html
<!DOCTYPE html>
<html lang="en">
<head><title>Links</title></head>
<body>
<p>See the <a href="https://go.dev/doc/">Go documentation</a> and
<a href="/golang/http-server/">the HTTP server article</a>.</p>
<p>Fish &amp; chips &lt;3</p>
</body>
</html>

The two anchors feed the link extraction example later in the article, and the escaped characters in the last paragraph show how entities look in the tree once the parser has decoded them.

Extracting list items with the tokenizer

The tokenizer is a state machine: Next advances to the following token and returns its type. Text inside an li element is collected by remembering whether the last start tag was li.

main.go
package main

import (
    "fmt"
    "io"
    "log"
    "os"
    "strings"

    "golang.org/x/net/html"
)

func main() {

    data, err := os.ReadFile("index.html")
    if err != nil {
        log.Fatal(err)
    }

    tkn := html.NewTokenizer(strings.NewReader(string(data)))

    var items []string
    var inLi bool

    for {
        tt := tkn.Next()

        if tt == html.ErrorToken {
            break
        }

        switch tt {
        case html.StartTagToken:
            tag := tkn.Token()
            inLi = tag.Data == "li"

        case html.EndTagToken:
            inLi = false

        case html.TextToken:
            text := strings.TrimSpace(tkn.Token().Data)
            if inLi && text != "" {
                items = append(items, text)
            }
            inLi = false
        }
    }

    if tkn.Err() != io.EOF {
        log.Fatal(tkn.Err())
    }

    fmt.Println(items)
}

The end of the document is reported as html.ErrorToken, and Err tells whether the stream ended normally with io.EOF or with a real failure. The EndTagToken case resets the flag, so text after </li> is ignored.

$ go run main.go
[red green blue yellow orange brown pink]

Walking the parse tree

html.Parse builds the document from the same input. The tree is searched with a recursive function that visits a node, then its children, then its siblings through NextSibling.

main.go
package main

import (
    "fmt"
    "log"
    "os"
    "strings"

    "golang.org/x/net/html"
)

func main() {

    f, err := os.Open("index.html")
    if err != nil {
        log.Fatal(err)
    }
    defer f.Close()

    doc, err := html.Parse(f)
    if err != nil {
        log.Fatal(err)
    }

    var items []string

    var walk func(n *html.Node)
    walk = func(n *html.Node) {

        if n.Type == html.ElementNode && n.Data == "li" {
            items = append(items, textContent(n))
        }

        for c := n.FirstChild; c != nil; c = c.NextSibling {
            walk(c)
        }
    }

    walk(doc)
    fmt.Println(items)
}

func textContent(n *html.Node) string {

    var sb strings.Builder

    var walk func(*html.Node)
    walk = func(n *html.Node) {
        if n.Type == html.TextNode {
            sb.WriteString(n.Data)
        }
        for c := n.FirstChild; c != nil; c = c.NextSibling {
            walk(c)
        }
    }

    walk(n)

    return strings.Join(strings.Fields(sb.String()), " ")
}

textContent concatenates the text of all descendants and collapses whitespace with strings.Fields. Unlike the tokenizer, the tree version also works when an element contains nested markup such as <li><b>red</b></li>, because it collects the text of the whole subtree.

$ go run main.go
[red green blue yellow orange brown pink]

Finding an element by id

The tree has no index, so a lookup by id is a full traversal. Once the node is found, html.Render serializes it back to HTML.

main.go
package main

import (
    "bytes"
    "fmt"
    "log"
    "os"

    "golang.org/x/net/html"
)

func main() {

    f, err := os.Open("index.html")
    if err != nil {
        log.Fatal(err)
    }
    defer f.Close()

    doc, err := html.Parse(f)
    if err != nil {
        log.Fatal(err)
    }

    node := byID(doc, "yellow")
    if node == nil {
        log.Fatal("no element with that id")
    }

    var buf bytes.Buffer
    if err := html.Render(&buf, node); err != nil {
        log.Fatal(err)
    }

    fmt.Println(buf.String())
    fmt.Println(node.Attr)
}

func byID(n *html.Node, id string) *html.Node {

    if n.Type == html.ElementNode {
        for _, a := range n.Attr {
            if a.Key == "id" && a.Val == id {
                return n
            }
        }
    }

    for c := n.FirstChild; c != nil; c = c.NextSibling {
        if found := byID(c, id); found != nil {
            return found
        }
    }

    return nil
}

The attributes are a slice of html.Attribute values with Namespace, Key and Val fields, in that order. The printed slice therefore reads as an empty namespace, the key id and the value yellow. Ordinary attributes have no namespace; the field is used only for attributes such as xlink:href in SVG.

$ go run main.go
<li id="yellow">yellow</li>
[{ id yellow}]

Extracting links and their text

The same traversal can select several elements and read one attribute from each. This is the core of a crawler: find a elements, take href, take the visible text.

main.go
package main

import (
    "fmt"
    "log"
    "os"
    "strings"

    "golang.org/x/net/html"
)

func main() {

    f, err := os.Open("links.html")
    if err != nil {
        log.Fatal(err)
    }
    defer f.Close()

    doc, err := html.Parse(f)
    if err != nil {
        log.Fatal(err)
    }

    var walk func(n *html.Node)
    walk = func(n *html.Node) {

        if n.Type == html.ElementNode && n.Data == "a" {
            for _, a := range n.Attr {
                if a.Key == "href" {
                    fmt.Printf("%-40s %s\n", a.Val, textContent(n))
                }
            }
        }

        for c := n.FirstChild; c != nil; c = c.NextSibling {
            walk(c)
        }
    }

    walk(doc)

    body := findElement(doc, "body")
    fmt.Println(strings.Join(strings.Fields(textContent(body)), " "))
}

func textContent(n *html.Node) string {

    var sb strings.Builder

    var walk func(*html.Node)
    walk = func(n *html.Node) {
        if n.Type == html.TextNode {
            sb.WriteString(n.Data)
        }
        for c := n.FirstChild; c != nil; c = c.NextSibling {
            walk(c)
        }
    }

    walk(n)
    return sb.String()
}

func findElement(n *html.Node, name string) *html.Node {

    if n.Type == html.ElementNode && n.Data == name {
        return n
    }

    for c := n.FirstChild; c != nil; c = c.NextSibling {
        if found := findElement(c, name); found != nil {
            return found
        }
    }

    return nil
}

textContent keeps the raw text here, so the paragraph printed at the end needs an extra Fields pass to lose the line breaks. Character references have already been decoded at this point: the entity &amp;amp; in the file became an ampersand, and &amp;lt; became a less-than sign.

$ go run main.go
https://go.dev/doc/                      Go documentation
/golang/http-server/                     the HTTP server article
See the Go documentation and the HTTP server article. Fish & chips <3

Reading a table into rows

A table is a tree of table, tr and td elements. Collecting the cells of every row produces a slice of records, which is what a scraper usually needs.

countries.html
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Countries</title></head>
<body>
<table>
    <thead>
    <tr><th>Id</th><th>Name</th><th>Population</th></tr>
    </thead>
    <tbody>
    <tr><td>1</td><td>China</td><td>1382050000</td></tr>
    <tr><td>2</td><td>India</td><td>1313210000</td></tr>
    <tr><td>3</td><td>USA</td><td>324666000</td></tr>
    <tr><td>4</td><td>Indonesia</td><td>260581000</td></tr>
    </tbody>
</table>
</body>
</html>

The header row uses th cells, so it is skipped by the search for td elements. The example prints each record as one line joined with a vertical bar.

main.go
package main

import (
    "fmt"
    "log"
    "os"
    "strings"

    "golang.org/x/net/html"
)

func main() {

    f, err := os.Open("countries.html")
    if err != nil {
        log.Fatal(err)
    }
    defer f.Close()

    doc, err := html.Parse(f)
    if err != nil {
        log.Fatal(err)
    }

    table := findElements(doc, "table")[0]

    for _, tr := range findElements(table, "tr") {

        var cells []string

        for _, td := range findElements(tr, "td") {
            cells = append(cells, textContent(td))
        }

        if len(cells) > 0 {
            fmt.Println(strings.Join(cells, " | "))
        }
    }
}

func findElements(n *html.Node, name string) []*html.Node {

    var found []*html.Node

    var walk func(*html.Node)
    walk = func(n *html.Node) {
        if n.Type == html.ElementNode && n.Data == name {
            found = append(found, n)
        }
        for c := n.FirstChild; c != nil; c = c.NextSibling {
            walk(c)
        }
    }

    walk(n)
    return found
}

func textContent(n *html.Node) string {

    var sb strings.Builder

    var walk func(*html.Node)
    walk = func(n *html.Node) {
        if n.Type == html.TextNode {
            sb.WriteString(n.Data)
        }
        for c := n.FirstChild; c != nil; c = c.NextSibling {
            walk(c)
        }
    }

    walk(n)

    return strings.Join(strings.Fields(sb.String()), " ")
}

findElements is not limited to one level: the call on table returns the header row and the four body rows, and the call on each row returns its cells. Indexing the first result of findElements(doc, "table") would panic on a document without a table, so real code checks the length first.

$ go run main.go
1 | China | 1382050000
2 | India | 1313210000
3 | USA | 324666000
4 | Indonesia | 260581000

What happens with malformed HTML

The parser repairs the document according to the HTML5 rules: it inserts the missing html, head and body elements and closes some tags automatically. Other tags stay open and swallow the following content.

broken.html
<html>
<body>
<h1>Report
<p>First paragraph
<p>Second <b>bold paragraph
<ul>
  <li>one
  <li>two
</ul>
</body>
</html>

Rendering the parsed body shows exactly what the tree looks like. The p and li elements were closed at the right places because the algorithm implies their end tags, while h1 and b were never closed and therefore contain their siblings.

main.go
package main

import (
    "bytes"
    "fmt"
    "log"
    "os"
    "strings"

    "golang.org/x/net/html"
)

func main() {

    f, err := os.Open("broken.html")
    if err != nil {
        log.Fatal(err)
    }
    defer f.Close()

    doc, err := html.Parse(f)
    if err != nil {
        log.Fatal(err)
    }

    body := findElement(doc, "body")

    var buf bytes.Buffer
    if err := html.Render(&buf, body); err != nil {
        log.Fatal(err)
    }

    fmt.Println(strings.TrimSpace(buf.String()))
}

func findElement(n *html.Node, name string) *html.Node {

    if n.Type == html.ElementNode && n.Data == name {
        return n
    }

    for c := n.FirstChild; c != nil; c = c.NextSibling {
        if found := findElement(c, name); found != nil {
            return found
        }
    }

    return nil
}

The rendered text keeps the original line breaks inside the text nodes, so the closing tags appear on their own lines. This output is a useful debugging aid when a selector does not match: the element hierarchy is probably not the one the markup suggests.

$ go run main.go
<body>
<h1>Report
<p>First paragraph
</p><p>Second <b>bold paragraph
</b></p><ul><b>
  <li>one
  </li><li>two
</li></b></ul><b>


</b></h1></body>

Parsing titles concurrently

Tokenizers work on any io.Reader, including an HTTP response body. The example below starts one goroutine per page, collects the titles under a mutex and sorts them, so the output does not depend on the order in which the requests finish.

main.go
package main

import (
    "fmt"
    "log"
    "net/http"
    "net/http/httptest"
    "slices"
    "strings"
    "sync"

    "golang.org/x/net/html"
)

func main() {

    pages := map[string]string{
        "/go":     "<html><head><title>Go</title></head><body>go</body></html>",
        "/python": "<html><head><title>Python</title></head><body>py</body></html>",
        "/rust":   "<html><head><title>Rust</title></head><body>rs</body></html>",
    }

    mux := http.NewServeMux()

    for path, body := range pages {
        mux.HandleFunc("GET "+path, func(w http.ResponseWriter, r *http.Request) {
            fmt.Fprint(w, body)
        })
    }

    srv := httptest.NewServer(mux)
    defer srv.Close()

    paths := []string{"/go", "/python", "/rust"}

    var mu sync.Mutex
    var titles []string
    var wg sync.WaitGroup

    for _, p := range paths {
        wg.Add(1)

        go func() {
            defer wg.Done()

            resp, err := http.Get(srv.URL + p)
            if err != nil {
                log.Println(err)
                return
            }
            defer resp.Body.Close()

            title := title(resp)

            mu.Lock()
            titles = append(titles, title)
            mu.Unlock()
        }()
    }

    wg.Wait()
    slices.Sort(titles)

    for _, t := range titles {
        fmt.Println(t)
    }
}

func title(resp *http.Response) string {

    tkn := html.NewTokenizer(resp.Body)
    var inTitle bool

    for {
        tt := tkn.Next()

        if tt == html.ErrorToken {
            return ""
        }

        switch tt {
        case html.StartTagToken:
            inTitle = tkn.Token().Data == "title"

        case html.TextToken:
            if inTitle {
                return strings.TrimSpace(tkn.Token().Data)
            }
        }
    }
}

The handler closes over body, which is safe because Go 1.22 creates a new variable for each iteration of the range loop. The local test server replaces the remote sites that older versions of this article fetched, so the output is always the same three titles.

$ go run main.go
Go
Python
Rust

Source

Go net/html package - reference

In this article we have tokenized and parsed HTML with golang.org/x/net/html, searched the document tree, read attributes and text, extracted a table, inspected the repair of malformed markup and scraped three pages concurrently.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Go tutorials.