Web scraping

suggest change

Web scraping means downloading web pages and extracting data from them. In Go it splits into two parts:

This article is about the second part. Examples use goquery for the parsing step because it's short:

go get github.com/PuerkitoBio/goquery golang.org/x/time/rate github.com/temoto/robotstxt

Every example runs against a local server created with net/http/httptest, so you can run it without network access and get the same output every time. httptest.NewServer starts a real HTTP server on 127.0.0.1 with a random port and its URL field holds the base address, such as http://127.0.0.1:52341. This is also how you should test your own scrapers: save a few real pages and serve them from httptest (see Testing HTTP requests).

Before scraping a site, check whether it has an API or a data export, read its terms of service, and keep the load you put on it low.

Fetching a page politely

http.Get uses http.DefaultClient, which has no timeout. A server that stops responding mid-transfer would block your scraper forever. A scraper should:

package main

import (
	"fmt"
	"io"
	"mime"
	"net/http"
	"net/http/httptest"
	"strings"
	"time"
)

const userAgent = "example-bot/1.0 (+https://example.com/bot)"
const maxBodySize = 2 << 20 // 2 MB

var client = &http.Client{Timeout: 10 * time.Second}

// fetch downloads an HTML page and returns its body.
func fetch(url string) ([]byte, error) {
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return nil, err
	}
	req.Header.Set("User-Agent", userAgent)
	req.Header.Set("Accept", "text/html")

	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("GET %s: %s", url, resp.Status)
	}
	mt, _, _ := mime.ParseMediaType(resp.Header.Get("Content-Type"))
	if mt != "text/html" {
		return nil, fmt.Errorf("GET %s: not HTML (%s)", url, mt)
	}
	// Read one byte more than the limit to detect oversized pages.
	body, err := io.ReadAll(io.LimitReader(resp.Body, maxBodySize+1))
	if err != nil {
		return nil, err
	}
	if len(body) > maxBodySize {
		return nil, fmt.Errorf("GET %s: page larger than %d bytes", url, maxBodySize)
	}
	return body, nil
}

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/{$}", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		fmt.Fprintf(w, "<p>Hello, %s</p>", r.UserAgent())
	})
	mux.HandleFunc("/data.json", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		fmt.Fprint(w, `{"a":1}`)
	})
	mux.HandleFunc("/big", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/html")
		fmt.Fprint(w, strings.Repeat("x", 3<<20))
	})
	srv := httptest.NewServer(mux)
	defer srv.Close()

	for _, path := range []string{"/", "/data.json", "/big", "/missing"} {
		body, err := fetch(srv.URL + path)
		if err != nil {
			fmt.Println("error:", strings.Replace(err.Error(), srv.URL, "", 1))
			continue
		}
		fmt.Printf("%s: %s\n", path, body)
	}
}
/: <p>Hello, example-bot/1.0 (+https://example.com/bot)</p>
error: GET /data.json: not HTML (application/json)
error: GET /big: page larger than 2097152 bytes
error: GET /missing: 404 Not Found

Notes:

If the page isn't UTF-8, convert it with charset.NewReader before parsing, as shown in Parsing HTML.

Crawling a site

A crawler starts from one URL, extracts links and visits them. The core is a queue of URLs to visit and a set of URLs already seen. The hard part is deciding when two links point to the same page. Before adding a link to the queue:

This crawler visits pages breadth-first and stops at a maximum depth:

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"

	"github.com/PuerkitoBio/goquery"
)

var site = map[string]string{
	"/": `<title>Home</title>
		<a href="/about">About</a> <a href="/blog/">Blog</a>
		<a href="https://go.dev/">Go</a> <a href="mailto:me@example.com">Mail</a>`,
	"/about": `<title>About</title><a href="/">Home</a> <a href="/about#team">Team</a>`,
	"/blog/": `<title>Blog</title>
		<a href="post-1">Post 1</a> <a href="./post-2?ref=list">Post 2</a>
		<a href="/blog/old">Old post</a>`,
	"/blog/post-1": `<title>Post 1</title><a href="../">Back</a>`,
	"/blog/post-2": `<title>Post 2</title><a href="post-1">Previous</a>`,
}

func siteHandler(w http.ResponseWriter, r *http.Request) {
	page, ok := site[r.URL.Path]
	if !ok {
		http.NotFound(w, r)
		return
	}
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	fmt.Fprint(w, page)
}

// normalize resolves href against base and returns a canonical URL,
// or "" if the link should not be followed.
func normalize(base *url.URL, href string) string {
	u, err := base.Parse(strings.TrimSpace(href))
	if err != nil {
		return ""
	}
	if u.Scheme != "http" && u.Scheme != "https" {
		return "" // mailto:, javascript:, ftp: ...
	}
	if u.Host != base.Host {
		return "" // stay on the same site
	}
	u.Fragment = "" // /about#team is the same page as /about
	u.RawQuery = "" // drop tracking parameters like ?ref=list
	return u.String()
}

type page struct {
	url   string
	title string
	links []string
}

func fetchPage(pageURL string) (*page, error) {
	resp, err := http.Get(pageURL)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("%s", resp.Status)
	}
	doc, err := goquery.NewDocumentFromReader(resp.Body)
	if err != nil {
		return nil, err
	}
	base := resp.Request.URL // final URL, after redirects
	p := &page{url: pageURL, title: doc.Find("title").Text()}
	doc.Find("a[href]").Each(func(_ int, a *goquery.Selection) {
		if link := normalize(base, a.AttrOr("href", "")); link != "" {
			p.links = append(p.links, link)
		}
	})
	return p, nil
}

// crawl visits pages breadth-first, up to maxDepth links away from start.
func crawl(start string, maxDepth int) {
	type item struct {
		url   string
		depth int
	}
	seen := map[string]bool{start: true}
	queue := []item{{start, 0}}
	for len(queue) > 0 {
		it := queue[0]
		queue = queue[1:]
		p, err := fetchPage(it.url)
		path := strings.TrimPrefix(it.url, srvURL)
		if err != nil {
			fmt.Printf("depth %d  %-14s error: %v\n", it.depth, path, err)
			continue
		}
		fmt.Printf("depth %d  %-14s %q\n", it.depth, path, p.title)
		if it.depth == maxDepth {
			continue
		}
		for _, link := range p.links {
			if !seen[link] {
				seen[link] = true
				queue = append(queue, item{link, it.depth + 1})
			}
		}
	}
}

var srvURL string

func main() {
	srv := httptest.NewServer(http.HandlerFunc(siteHandler))
	defer srv.Close()
	srvURL = srv.URL
	crawl(srv.URL+"/", 2)
}
depth 0  /              "Home"
depth 1  /about         "About"
depth 1  /blog/         "Blog"
depth 2  /blog/post-1   "Post 1"
depth 2  /blog/post-2   "Post 2"
depth 2  /blog/old      error: 404 Not Found

Each page is visited once, even though two pages link to /blog/post-1, several pages link back to pages already seen, and /about#team links to /about. The links to go.dev and mailto: are skipped.

URLs are marked as seen when they're added to the queue, not when they're visited. Otherwise a page linked from several pages at the same level would be queued several times.

Breadth-first order visits pages closest to the start first, which is usually what you want: if you stop early you get the most important pages. A depth-first crawler (using a stack instead of a queue) tends to wander deep into archives and pagination.

Concurrent crawling

Fetching pages one at a time is slow, because most of the time is spent waiting for the network. Goroutines make it easy to fetch many pages at once, but you must limit how many requests are in flight. Starting a goroutine per link with no limit would send hundreds of requests to the server at once.

The crawler below starts a goroutine for every new URL but uses a buffered channel as a semaphore, so at most 4 requests run at the same time. The test server records the maximum number of requests it handled concurrently:

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"net/url"
	"slices"
	"strings"
	"sync"
	"sync/atomic"
	"time"

	"github.com/PuerkitoBio/goquery"
)

// A test site with 30 pages: the home page links to /p/1 .. /p/10,
// and every /p/N links to /p/2N and /p/2N+1 (while N <= 30).
func newSite() (*httptest.Server, *atomic.Int32) {
	var active, maxActive atomic.Int32
	h := func(w http.ResponseWriter, r *http.Request) {
		n := active.Add(1)
		defer active.Add(-1)
		for {
			m := maxActive.Load()
			if n <= m || maxActive.CompareAndSwap(m, n) {
				break
			}
		}
		time.Sleep(50 * time.Millisecond) // simulate a slow server

		var b strings.Builder
		if r.URL.Path == "/" {
			b.WriteString("<title>Home</title>")
			for i := 1; i <= 10; i++ {
				fmt.Fprintf(&b, `<a href="/p/%d">%d</a>`, i, i)
			}
		} else {
			var n int
			if _, err := fmt.Sscanf(r.URL.Path, "/p/%d", &n); err != nil || n > 30 {
				http.NotFound(w, r)
				return
			}
			fmt.Fprintf(&b, `<title>Page %d</title><a href="/">Home</a>`, n)
			for _, c := range []int{2 * n, 2*n + 1} {
				if c <= 30 {
					fmt.Fprintf(&b, `<a href="/p/%d">%d</a>`, c, c)
				}
			}
		}
		w.Header().Set("Content-Type", "text/html")
		fmt.Fprint(w, b.String())
	}
	return httptest.NewServer(http.HandlerFunc(h)), &maxActive
}

type Crawler struct {
	maxDepth int
	sem      chan struct{} // limits concurrent requests
	wg       sync.WaitGroup

	mu     sync.Mutex
	seen   map[string]bool
	titles map[string]string
}

func NewCrawler(concurrency, maxDepth int) *Crawler {
	return &Crawler{
		maxDepth: maxDepth,
		sem:      make(chan struct{}, concurrency),
		seen:     map[string]bool{},
		titles:   map[string]string{},
	}
}

// visit schedules u for crawling unless it was already seen.
func (c *Crawler) visit(u string, depth int) {
	c.mu.Lock()
	defer c.mu.Unlock()
	if c.seen[u] || depth > c.maxDepth {
		return
	}
	c.seen[u] = true
	c.wg.Go(func() { c.crawl(u, depth) })
}

func (c *Crawler) crawl(pageURL string, depth int) {
	c.sem <- struct{}{} // acquire a slot
	title, links, err := fetchLinks(pageURL)
	<-c.sem // release it before scheduling more work
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	c.mu.Lock()
	c.titles[pageURL] = title
	c.mu.Unlock()
	for _, link := range links {
		c.visit(link, depth+1)
	}
}

func (c *Crawler) Run(start string) map[string]string {
	c.visit(start, 0)
	c.wg.Wait()
	return c.titles
}

func fetchLinks(pageURL string) (string, []string, error) {
	resp, err := http.Get(pageURL)
	if err != nil {
		return "", nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return "", nil, fmt.Errorf("GET %s: %s", pageURL, resp.Status)
	}
	doc, err := goquery.NewDocumentFromReader(resp.Body)
	if err != nil {
		return "", nil, err
	}
	var links []string
	doc.Find("a[href]").Each(func(_ int, a *goquery.Selection) {
		u, err := resp.Request.URL.Parse(a.AttrOr("href", ""))
		if err == nil && u.Host == resp.Request.URL.Host {
			u.Fragment = ""
			links = append(links, u.String())
		}
	})
	return doc.Find("title").Text(), links, nil
}

func main() {
	srv, maxActive := newSite()
	defer srv.Close()

	start := time.Now()
	titles := NewCrawler(4, 10).Run(srv.URL + "/")
	elapsed := time.Since(start)

	paths := make([]string, 0, len(titles))
	for u := range titles {
		p, _ := url.Parse(u)
		paths = append(paths, p.Path)
	}
	slices.Sort(paths)
	fmt.Println("pages:", len(titles))
	fmt.Println("first few:", paths[:5])
	fmt.Println("max concurrent requests:", maxActive.Load())
	fmt.Println("faster than sequential:", elapsed < 31*50*time.Millisecond)
}
pages: 31
first few: [/ /p/1 /p/10 /p/11 /p/12]
max concurrent requests: 4
faster than sequential: true

How it works:

An alternative design is a fixed pool of N worker goroutines reading URLs from a channel. It's harder to get right for crawling, because workers also produce new URLs: if they send to a full channel that only they read from, everything deadlocks. The goroutine-per-URL design avoids that, and goroutines are cheap.

For a long-running crawler, also pass a context.Context down to http.NewRequestWithContext so you can stop the crawl on Ctrl+C or after a deadline, and use golang.org/x/sync/errgroup if the first error should cancel everything.

Rate limiting

Limiting concurrency is not the same as limiting the request rate. With 4 parallel requests to a fast server you can still send hundreds of requests per second. Polite scrapers limit the rate, typically to one request every second or few seconds per site.

golang.org/x/time/rate implements a token bucket. rate.NewLimiter(r, b) allows r events per second on average with bursts of up to b. Wait(ctx) blocks until the next event is allowed:

package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"
	"sync"
	"time"

	"golang.org/x/time/rate"
)

func main() {
	start := time.Now()
	var mu sync.Mutex
	var hits []time.Duration
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		mu.Lock()
		hits = append(hits, time.Since(start).Round(100*time.Millisecond))
		mu.Unlock()
	}))
	defer srv.Close()

	// 5 requests per second, bursts of up to 2 requests.
	limiter := rate.NewLimiter(rate.Limit(5), 2)
	ctx := context.Background()

	var wg sync.WaitGroup
	for i := range 8 {
		wg.Go(func() {
			// Wait blocks until the limiter allows one more event.
			if err := limiter.Wait(ctx); err != nil {
				fmt.Println(err)
				return
			}
			resp, err := http.Get(fmt.Sprintf("%s/page/%d", srv.URL, i))
			if err != nil {
				fmt.Println(err)
				return
			}
			resp.Body.Close()
		})
	}
	wg.Wait()
	fmt.Println("request times:", hits)
}
request times: [0s 0s 200ms 400ms 600ms 800ms 1s 1.2s]

The bucket starts full, so the first 2 requests go out immediately (the burst), and after that one request every 200 ms. Use rate.Every(2 * time.Second) to express "one request every 2 seconds", and a burst of 1 to never send two requests back to back.

A crawler that visits several sites should limit each site separately. A neat way to do it is a custom http.RoundTripper: wrap the transport and every request made with the client gets rate limited, no matter which part of the code sends it:

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"sync"
	"time"

	"golang.org/x/time/rate"
)

// limitedTransport is an http.RoundTripper that rate limits
// requests separately for each host.
type limitedTransport struct {
	next  http.RoundTripper
	every time.Duration

	mu       sync.Mutex
	limiters map[string]*rate.Limiter
}

func (t *limitedTransport) limiter(host string) *rate.Limiter {
	t.mu.Lock()
	defer t.mu.Unlock()
	l, ok := t.limiters[host]
	if !ok {
		l = rate.NewLimiter(rate.Every(t.every), 1)
		t.limiters[host] = l
	}
	return l
}

func (t *limitedTransport) RoundTrip(req *http.Request) (*http.Response, error) {
	// Wait respects the request's context: cancellation stops the wait.
	if err := t.limiter(req.URL.Host).Wait(req.Context()); err != nil {
		return nil, err
	}
	return t.next.RoundTrip(req)
}

func main() {
	start := time.Now()
	var mu sync.Mutex
	hits := map[string][]time.Duration{}
	handler := func(name string) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			mu.Lock()
			hits[name] = append(hits[name], time.Since(start).Round(100*time.Millisecond))
			mu.Unlock()
		})
	}
	a := httptest.NewServer(handler("a"))
	defer a.Close()
	b := httptest.NewServer(handler("b"))
	defer b.Close()

	client := &http.Client{
		Timeout: 10 * time.Second,
		Transport: &limitedTransport{
			next:     http.DefaultTransport,
			every:    300 * time.Millisecond,
			limiters: map[string]*rate.Limiter{},
		},
	}

	var wg sync.WaitGroup
	for range 3 {
		for _, base := range []string{a.URL, b.URL} {
			wg.Go(func() {
				resp, err := client.Get(base + "/")
				if err != nil {
					fmt.Println(err)
					return
				}
				resp.Body.Close()
			})
		}
	}
	wg.Wait()
	fmt.Println("host a:", hits["a"])
	fmt.Println("host b:", hits["b"])
}
host a: [0s 300ms 600ms]
host b: [0s 300ms 600ms]

Each host gets 3 requests spaced 300 ms apart, but the two hosts don't slow each other down. Wait takes the request's context, so a client Timeout or a cancelled context also aborts the wait. Note that the time spent waiting counts towards Client.Timeout.

Retries with backoff

Networks and servers fail. A scraper that runs for hours will see connection resets, timeouts, 502 Bad Gateway and 503 Service Unavailable. Those are worth retrying. Errors like 404 Not Found or 403 Forbidden are not: retrying won't change the answer.

429 Too Many Requests means you are going too fast. The server may send a Retry-After header with the number of seconds to wait, or an HTTP date. Honour it.

Wait longer after each failure (exponential backoff) and add randomness (jitter), so that many clients that failed at the same moment don't retry at the same moment:

package main

import (
	"context"
	"fmt"
	"io"
	"math/rand/v2"
	"net/http"
	"net/http/httptest"
	"strconv"
	"sync"
	"time"
)

// retryable reports whether a request that got status code should be retried.
func retryable(code int) bool {
	return code == http.StatusTooManyRequests ||
		(code >= 500 && code != http.StatusNotImplemented)
}

// retryAfter parses the Retry-After header, which holds either
// a number of seconds or an HTTP date.
func retryAfter(h string) (time.Duration, bool) {
	if h == "" {
		return 0, false
	}
	if secs, err := strconv.Atoi(h); err == nil && secs >= 0 {
		return time.Duration(secs) * time.Second, true
	}
	if t, err := http.ParseTime(h); err == nil {
		return max(time.Until(t), 0), true
	}
	return 0, false
}

// getWithRetry does a GET request, retrying network errors and
// retryable status codes with exponential backoff and jitter.
func getWithRetry(ctx context.Context, client *http.Client, url string, attempts int) ([]byte, error) {
	backoff := 100 * time.Millisecond
	for attempt := 1; ; attempt++ {
		req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
		if err != nil {
			return nil, err
		}
		var wait time.Duration
		resp, err := client.Do(req)
		if err == nil {
			if resp.StatusCode == http.StatusOK {
				defer resp.Body.Close()
				return io.ReadAll(resp.Body)
			}
			resp.Body.Close()
			err = fmt.Errorf("%s", resp.Status)
			if !retryable(resp.StatusCode) {
				return nil, err // 404, 403 etc.: retrying won't help
			}
			wait, _ = retryAfter(resp.Header.Get("Retry-After"))
		}
		if attempt == attempts {
			return nil, fmt.Errorf("giving up after %d attempts: %w", attempts, err)
		}
		if wait == 0 {
			// Full jitter: random duration in [backoff/2, backoff*3/2).
			wait = backoff/2 + rand.N(backoff)
			backoff *= 2
		}
		fmt.Printf("  attempt %d: %v, retrying\n", attempt, err)
		select {
		case <-time.After(wait):
		case <-ctx.Done():
			return nil, ctx.Err()
		}
	}
}

func main() {
	var mu sync.Mutex
	calls := map[string]int{}
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		mu.Lock()
		calls[r.URL.Path]++
		n := calls[r.URL.Path]
		mu.Unlock()
		switch {
		case r.URL.Path == "/flaky" && n <= 2:
			http.Error(w, "try later", http.StatusServiceUnavailable)
		case r.URL.Path == "/limited" && n == 1:
			w.Header().Set("Retry-After", "1")
			http.Error(w, "slow down", http.StatusTooManyRequests)
		case r.URL.Path == "/broken":
			http.Error(w, "oops", http.StatusInternalServerError)
		case r.URL.Path == "/missing":
			http.NotFound(w, r)
		default:
			fmt.Fprintf(w, "ok after %d calls", n)
		}
	}))
	defer srv.Close()

	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	client := &http.Client{Timeout: 5 * time.Second}
	for _, path := range []string{"/flaky", "/limited", "/broken", "/missing"} {
		fmt.Println(path)
		start := time.Now()
		body, err := getWithRetry(ctx, client, srv.URL+path, 4)
		took := time.Since(start).Round(time.Second)
		if err != nil {
			fmt.Println("  error:", err)
			continue
		}
		fmt.Printf("  %s (took ~%v)\n", body, took)
	}
}
/flaky
  attempt 1: 503 Service Unavailable, retrying
  attempt 2: 503 Service Unavailable, retrying
  ok after 3 calls (took ~0s)
/limited
  attempt 1: 429 Too Many Requests, retrying
  ok after 2 calls (took ~1s)
/broken
  attempt 1: 500 Internal Server Error, retrying
  attempt 2: 500 Internal Server Error, retrying
  attempt 3: 500 Internal Server Error, retrying
  error: giving up after 4 attempts: 500 Internal Server Error
/missing
  error: 404 Not Found

Notes:

Respecting robots.txt

robots.txt at the root of a site tells crawlers which paths they shouldn't visit and sometimes how long to wait between requests (Crawl-delay). It is advisory, but every well-behaved crawler follows it. The robotstxt package parses it:

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"net/url"
	"time"

	"github.com/temoto/robotstxt"
)

const robots = `User-agent: *
Disallow: /admin/
Disallow: /search
Allow: /search/help

User-agent: example-bot
Disallow: /private/
Crawl-delay: 2

Sitemap: https://example.com/sitemap.xml
`

// fetchRobots downloads and parses robots.txt of the site that pageURL belongs to.
func fetchRobots(client *http.Client, pageURL string) (*robotstxt.RobotsData, error) {
	u, err := url.Parse(pageURL)
	if err != nil {
		return nil, err
	}
	robotsURL := u.Scheme + "://" + u.Host + "/robots.txt"
	resp, err := client.Get(robotsURL)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	// FromResponse interprets the status code: 4xx (e.g. no robots.txt)
	// allows everything, 5xx disallows everything.
	return robotstxt.FromResponse(resp)
}

func main() {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path == "/robots.txt" {
			fmt.Fprint(w, robots)
			return
		}
		http.NotFound(w, r)
	}))
	defer srv.Close()
	client := &http.Client{Timeout: 10 * time.Second}

	data, err := fetchRobots(client, srv.URL+"/some/page")
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("sitemaps:", data.Sitemaps)
	for _, agent := range []string{"example-bot/1.0", "other-bot"} {
		// FindGroup picks the most specific User-agent group.
		group := data.FindGroup(agent)
		fmt.Printf("%s (crawl delay %v):\n", agent, group.CrawlDelay)
		for _, p := range []string{"/", "/admin/users", "/search?q=go", "/search/help", "/private/x"} {
			fmt.Printf("  %-14s %v\n", p, group.Test(p))
		}
	}
}
sitemaps: [https://example.com/sitemap.xml]
example-bot/1.0 (crawl delay 2s):
  /              true
  /admin/users   true
  /search?q=go   true
  /search/help   true
  /private/x     false
other-bot (crawl delay 0s):
  /              true
  /admin/users   false
  /search?q=go   false
  /search/help   true
  /private/x     true

Some things worth noticing:

Fetch robots.txt once per host, cache the parsed result, and check group.Test(u.Path) (or u.RequestURI() to include the query) before every request.

Following pagination

Listings like search results, product catalogs and blog archives are split into pages. Rather than guessing URLs like ?page=2, follow the link the page gives you. Many sites mark it with rel="next", either on an <a> or on a <link> in <head>; otherwise look for a link with a stable class or text such as "Next".

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"strconv"
	"strings"

	"github.com/PuerkitoBio/goquery"
)

var products = []string{"Apple", "Banana", "Cherry", "Date", "Elderberry", "Fig", "Grape"}

const perPage = 3

func productsHandler(w http.ResponseWriter, r *http.Request) {
	page, _ := strconv.Atoi(r.URL.Query().Get("page"))
	page = max(page, 1)
	start := (page - 1) * perPage
	end := min(start+perPage, len(products))
	var b strings.Builder
	b.WriteString("<ul>")
	for i := start; i < end; i++ {
		fmt.Fprintf(&b, `<li class="product">%s</li>`, products[i])
	}
	b.WriteString("</ul>")
	if end < len(products) {
		fmt.Fprintf(&b, `<a rel="next" href="?page=%d">Next &raquo;</a>`, page+1)
	}
	w.Header().Set("Content-Type", "text/html")
	fmt.Fprint(w, b.String())
}

// scrapeAll follows rel="next" links starting at pageURL and
// returns the products from all pages.
func scrapeAll(pageURL string, maxPages int) ([]string, error) {
	var all []string
	seen := map[string]bool{}
	for i := 0; pageURL != "" && i < maxPages; i++ {
		if seen[pageURL] {
			break // a "next" link pointing back: avoid an infinite loop
		}
		seen[pageURL] = true

		resp, err := http.Get(pageURL)
		if err != nil {
			return all, err
		}
		if resp.StatusCode != http.StatusOK {
			resp.Body.Close()
			return all, fmt.Errorf("GET %s: %s", pageURL, resp.Status)
		}
		doc, err := goquery.NewDocumentFromReader(resp.Body)
		resp.Body.Close()
		if err != nil {
			return all, err
		}
		doc.Find("li.product").Each(func(_ int, s *goquery.Selection) {
			all = append(all, s.Text())
		})
		fmt.Printf("%s: %d products\n", resp.Request.URL.RequestURI(), doc.Find("li.product").Length())

		pageURL = ""
		if href, ok := doc.Find(`a[rel="next"]`).Attr("href"); ok {
			next, err := resp.Request.URL.Parse(href)
			if err != nil {
				return all, err
			}
			pageURL = next.String()
		}
	}
	return all, nil
}

func main() {
	srv := httptest.NewServer(http.HandlerFunc(productsHandler))
	defer srv.Close()

	all, err := scrapeAll(srv.URL+"/products", 100)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(all)
}
/products: 3 products
/products?page=2: 3 products
/products?page=3: 1 products
[Apple Banana Cherry Date Elderberry Fig Grape]

The loop stops when there is no next link. The seen set and maxPages protect against sites whose last page links to itself or back to the first page, which would otherwise loop forever. The href is relative (?page=2), so it's resolved against the URL of the current page.

When the data comes from a JSON API with cursors ("next_cursor": "abc"), the loop is the same: request, append results, repeat while the cursor is non-empty. Check the browser's developer tools network tab: pages that load data with JavaScript often call such an API, and scraping the JSON is far easier and more reliable than scraping HTML.

Colly: a scraping framework

Colly packages everything above: link resolution, deduplication of visited URLs, depth limits, domain filters, parallelism and delays per domain, and callbacks with goquery selections. For a crawler that just collects data, it saves a lot of code:

go get github.com/gocolly/colly/v2
package main

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

	"github.com/gocolly/colly/v2"
)

var site = map[string]string{
	"/": `<title>Home</title>
		<a href="/about">About</a> <a href="/blog/">Blog</a>
		<a href="https://go.dev/">Go</a>`,
	"/about": `<title>About</title><a href="/">Home</a>`,
	"/blog/": `<title>Blog</title>
		<a href="post-1">Post 1</a> <a href="post-2">Post 2</a>
		<a href="/blog/old">Old post</a>`,
	"/blog/post-1": `<title>Post 1</title><a href="../">Back</a>`,
	"/blog/post-2": `<title>Post 2</title><a href="post-1">Previous</a>`,
}

func main() {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		page, ok := site[r.URL.Path]
		if !ok {
			http.NotFound(w, r)
			return
		}
		w.Header().Set("Content-Type", "text/html")
		fmt.Fprint(w, page)
	}))
	defer srv.Close()

	c := colly.NewCollector(
		colly.AllowedDomains("127.0.0.1"), // skips go.dev
		colly.MaxDepth(3),
		colly.Async(true),
		colly.UserAgent("example-bot/1.0 (+https://example.com/bot)"),
	)
	c.SetRequestTimeout(10 * time.Second)
	// At most 2 parallel requests per domain, with a random delay between them.
	c.Limit(&colly.LimitRule{
		DomainGlob:  "*",
		Parallelism: 2,
		RandomDelay: 100 * time.Millisecond,
	})

	var mu sync.Mutex
	var results []string

	// Called for every element matching the CSS selector.
	c.OnHTML("a[href]", func(e *colly.HTMLElement) {
		// Visit resolves relative URLs and skips already visited ones.
		e.Request.Visit(e.Attr("href"))
	})
	c.OnHTML("title", func(e *colly.HTMLElement) {
		mu.Lock()
		defer mu.Unlock()
		results = append(results, fmt.Sprintf("%-13s %s", e.Request.URL.Path, e.Text))
	})
	c.OnError(func(r *colly.Response, err error) {
		mu.Lock()
		defer mu.Unlock()
		results = append(results, fmt.Sprintf("%-13s error: %v", r.Request.URL.Path, err))
	})

	c.Visit(srv.URL + "/")
	c.Wait() // needed in async mode

	slices.Sort(results)
	fmt.Println(strings.Join(results, "\n"))
}
/             Home
/about        About
/blog/        Blog
/blog/old     error: Not Found
/blog/post-1  Post 1
/blog/post-2  Post 2

Colly is a good fit for straightforward crawls. When you need precise control over retries, per-host scheduling or storage, the standard library pieces shown earlier are easy to combine.

Pages that need JavaScript

All the techniques above see only the HTML the server sends. If the data is rendered by JavaScript in the browser, the HTML will contain an empty <div id="app">. First look for the JSON API the page calls, or for data embedded in a <script type="application/json"> tag. If neither exists, drive a real headless browser with chromedp, which controls Chrome through the DevTools protocol. It's much slower and heavier, so use it only for the pages that need it.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents