---
title: "Extract links and link text from HTML in Go"
url: https://recursiveai.org/onehtml/go/cookbook/extract-links-and-anchor-text/
description: "Extract each anchor’s href and link text from HTML in Go, including nested text, and resolve relative hrefs against a base URL when needed."
version: "1.1.1"
---

# Extract links and link text from HTML in Go

**onehtml-go** is a free, open-source HTML parser for Go from Recursive AI, with CSS selectors, computed styles, lossless editing and accessibility checks. MIT or Apache-2.0, no dependencies.

[pkg.go.dev](https://pkg.go.dev/recursiveai.org/go/onehtml) · [GitHub](https://github.com/recursive-ai-oss/onehtml-go) · [Docs](https://recursiveai.org/onehtml/go/docs/) · [Download example (.zip)](https://recursiveai.org/onehtml/go/cookbook/extract-links-and-anchor-text/extract-links-and-anchor-text.zip)

Call `doc.Select("a[href]")`, then read each anchor’s `href` and `TextContent()`. Requires Go 1.24 or later.

```shell
go get recursiveai.org/go/onehtml
```

```go
package main

import (
	"fmt"
	"log"
	"strings"

	"recursiveai.org/go/onehtml"
)

func main() {
	const html = `<nav>
  <a href="/docs">Read <b>the docs</b></a>
  <a href="#contact">Contact</a>
  <a>Coming soon</a>
</nav>`
	doc, err := onehtml.Parse(strings.NewReader(html))
	if err != nil {
		log.Fatal(err)
	}
	links, err := doc.Select("a[href]")
	if err != nil {
		log.Fatal(err)
	}
	for _, link := range links {
		href, _ := link.Get("href") // Guaranteed by [href].
		text := strings.TrimSpace(link.TextContent())
		fmt.Printf("%s → %s\n", text, href)
	}
}
```

Paste the code above into main.go, run `go mod init example` and `go get recursiveai.org/go/onehtml`, then `go run .`; or unzip [the example](https://recursiveai.org/onehtml/go/cookbook/extract-links-and-anchor-text/extract-links-and-anchor-text.zip) and `go run .`.

```text
Read the docs → /docs
Contact → #contact
```

An anchor without `href` is skipped. The extracted destinations are not resolved or fetched. The example stops on a parse or selector error; a document with no matching links prints nothing.

## Variations

For absolute URLs, add `"net/url"` to the imports. Before the loop, parse the page URL, then replace the loop with this version (`links` is the same slice):

```go
base, err := url.Parse("https://example.com/guide")
if err != nil {
    log.Fatal(err)
}
for _, link := range links {
    href, _ := link.Get("href")
    target, err := base.Parse(href)
    if err != nil {
        log.Printf("skip %q: %v", href, err)
        continue
    }
    text := strings.TrimSpace(link.TextContent())
    fmt.Printf("%s → %s\n", text, target)
}
```

```text
Read the docs → https://example.com/docs
Contact → https://example.com/guide#contact
```

## Related recipes

- [Parse HTML and query CSS selectors in Go](https://recursiveai.org/onehtml/go/cookbook/parse-html-and-query-css-selectors/)

## The short answer

Query `a[href]`, call `Get("href")` for the destination and `TextContent()` for the anchor’s text, and keep the two together. The destination is the parsed attribute value, not an automatically expanded URL. Resolve it separately if you need absolute links.

## How do I extract all links from a webpage in Go?

First get the HTML you want to inspect, then parse it and select `a[href]`. That selector matches `<a>` elements with an `href` attribute, not `<link>` metadata, image sources, or `<a>` placeholders without a destination. If you only need links in navigation, narrow the selector to `nav a[href]`. With the document-wide selector, you get one match per anchor in document order, including separate anchors that lead to the same destination. Keep the duplicates if you’re auditing where links appear; collapse them only if you’re building a list of destinations.

The parser doesn’t request the page, follow the links, or run scripts that would construct anchors after load. Use a file, an HTTP response body, or already rendered HTML as input, depending on where the links you need are created. If `href` is present but empty, the selector still matches; skip empty values explicitly if your link list should exclude them.

## How can I extract link text from HTML?

Use [`TextContent()`](https://pkg.go.dev/recursiveai.org/go/onehtml@v1.1.1#Node.TextContent) on the matched anchor. It concatenates descendant text, so the `b` element in the sample contributes “the docs” without contributing its tags. `strings.TrimSpace` removes whitespace at the ends, not between words. The result is DOM text, not a measurement of what a browser displays or the accessible name for the link. For example, an image-only anchor can have no descendant text even when its image has an `alt` attribute. Don’t interpret an empty string from `TextContent()` as proof that the anchor has no accessible label.

## How do relative URLs work when extracting links?

An `href` like `/docs` is relative to the site root, while `#contact` stays on the same page and changes the fragment. Other paths, such as `next.html`, are relative to the base URL’s directory. Use Go’s [`URL.Parse`](https://pkg.go.dev/net/url#URL.Parse) as in the variation rather than concatenating strings. An absolute reference is already independent of the base.

Use the document’s effective base when you want links to resolve as they would in a browser. In HTML, a [`<base href>` element](https://html.spec.whatwg.org/multipage/semantics.html#the-base-element) can change that base; the variation deliberately uses a known page URL for markup without one. URL resolution does not check whether a target exists.
