Web scraping
Web scraping with Go and Colly
Colly gives Go a compact, callback driven scraping framework. You describe what to do with each element and each error, set limits per domain, and let the collector handle the crawling.
How Colly is organized
Colly centers on a collector: an object that holds settings (allowed domains, depth, user agent, limits) and a set of callbacks. When you call Visit, the collector fetches the page and fires your callbacks in a fixed order: OnRequest before sending, OnResponse when a successful response arrives, OnHTML for each element matching a selector, OnScraped after all HTML callbacks, and OnError when something fails. Most of a Colly program is these callbacks.
Install
go mod init example.com/scraper
go get github.com/gocolly/colly/v2
The import path includes /v2. Older tutorials that import github.com/gocolly/colly without it refer to the first major version.
A configured collector
package main
import (
"log"
"time"
colly "github.com/gocolly/colly/v2"
)
func newCollector() *colly.Collector {
c := colly.NewCollector(
colly.AllowedDomains("jobs.example.org"),
colly.MaxDepth(3),
colly.Async(true),
colly.UserAgent("Mozilla/5.0 (X11; Linux x86_64) openings-tracker/1.3"),
)
c.SetRequestTimeout(25 * time.Second)
if err := c.Limit(&colly.LimitRule{
DomainGlob: "*example.org*",
Parallelism: 2,
Delay: time.Second,
RandomDelay: 1500 * time.Millisecond,
}); err != nil {
log.Fatal(err)
}
return c
}
AllowedDomains keeps the crawl from wandering onto other sites through outbound links. MaxDepth limits how many link hops from the start page are followed. With Async(true), requests run in goroutines, and the LimitRule decides how many may run at once for matching domains and how long to wait between them. The random delay is added on top of the fixed one, which spreads requests out naturally.
Callbacks for data and links
OnHTML takes a CSS selector (Colly uses goquery under the hood) and a function that receives each matching element. Helper methods such as ChildText and ChildAttr read inside the element.
type Opening struct {
Title, Team, Link string
}
func register(c *colly.Collector, out chan<- Opening) {
c.OnRequest(func(r *colly.Request) {
r.Headers.Set("Accept-Language", "en-US,en;q=0.8")
})
c.OnHTML("div.opening", func(e *colly.HTMLElement) {
out <- Opening{
Title: e.ChildText("h2"),
Team: e.ChildText(".team"),
Link: e.Request.AbsoluteURL(e.ChildAttr("a.apply", "href")),
}
})
c.OnHTML("nav.pager a[rel=next]", func(e *colly.HTMLElement) {
if err := e.Request.Visit(e.Attr("href")); err != nil {
log.Println("pager skipped:", err)
}
})
c.OnError(func(r *colly.Response, err error) {
log.Printf("error %d on %s: %v", r.StatusCode, r.Request.URL, err)
})
}
e.Request.Visit resolves relative links against the current page and respects the collector's domain and depth rules. Colly also skips URLs it has already visited, so a pager that links back to page one does not create a loop.
Safe output from goroutines
In async mode, callbacks run concurrently. Writing to a shared slice or file from several callbacks at once is a data race. Sending results to a channel, with one goroutine writing them out, avoids locks entirely.
func main() {
c := newCollector()
results := make(chan Opening, 64)
register(c, results)
done := make(chan struct{})
go func() {
defer close(done)
w := csv.NewWriter(os.Stdout)
defer w.Flush()
_ = w.Write([]string{"title", "team", "link"})
for o := range results {
_ = w.Write([]string{o.Title, o.Team, o.Link})
}
}()
if err := c.Visit("https://jobs.example.org/openings"); err != nil {
log.Fatal(err)
}
c.Wait()
close(results)
<-done
}
Add encoding/csv and os to the imports. c.Wait() blocks until every queued request has finished; only then is it safe to close the channel. Forgetting Wait in async mode is the most common reason a Colly program exits with no output.
Errors and status codes
Colly treats responses with a status of 400 or more as errors and sends them to OnError, not OnResponse. That is convenient for logging, and it is where you handle blocks. The *colly.Response still carries the status code, headers and body, so you can inspect what came back. If you would rather receive error pages in OnResponse and OnHTML, set c.ParseHTTPErrorResponse = true.
A request can be repeated with r.Request.Retry(). Keep a retry budget, for example in the request context, so a page that always fails does not repeat forever:
c.OnError(func(r *colly.Response, err error) {
tries, _ := strconv.Atoi(r.Ctx.Get("tries"))
if (r.StatusCode == 429 || r.StatusCode >= 500) && tries < 3 {
r.Ctx.Put("tries", strconv.Itoa(tries+1))
time.Sleep(time.Duration(2<<tries) * time.Second)
_ = r.Request.Retry()
}
})
Prefer a backoff that grows with each attempt over a fixed pause, and log every retry with the URL and status. If most retries come from one host, lower that host's Parallelism or raise its Delay instead of adding more attempts.
Retrying after a challenge
When a site behind AWS WAF answers with its puzzle page, the response has status 405 and contains gokuProps, so it lands in OnError. Solve the challenge with an API call, store the returned cookie for the site, and retry:
if r.StatusCode == 405 && bytes.Contains(r.Body, []byte("gokuProps")) {
token, err := wafCookie(r.Request.URL.String())
if err == nil {
_ = c.SetCookies(r.Request.URL.String(), []*http.Cookie{{Name: "aws-waf-token", Value: token, Path: "/"}})
_ = r.Request.Retry()
}
}
wafCookie is your function that posts an AntiAwsWafTaskProxyLess task and polls for solution.cookie; the AWS WAF in Go guide contains one, and the polling pattern is the same as in the reCAPTCHA v2 Go guide. Colly's cookie jar then sends the token with every following request to that host. Because callbacks run in goroutines, use a mutex or sync.Once per host so that ten blocked requests do not trigger ten solves at once.
Separate collectors for lists and details
Listing pages and detail pages usually need different callbacks and sometimes different limits. Rather than one collector with selectors that try to cover both, create a second collector with c.Clone(). The clone copies the configuration (domains, user agent, limits) but starts with no callbacks, so you can register detail parsing on it alone. In the listing collector's OnHTML, call detail.Visit(link) instead of e.Request.Visit, and remember to call Wait() on both in async mode.
The extensions package adds small helpers that are easy to attach. extensions.Referer(c) sets the Referer header from the page that linked to each request, which is what a browser does and what some sites expect. Import it from github.com/gocolly/colly/v2/extensions. Keep the user agent fixed for a crawl unless you have a reason to change it; a stable, realistic identity is usually less suspicious than a random one per request.
Polite crawling checklist
- Keep
Parallelismlow per domain and useRandomDelay. - Set
c.IgnoreRobotsTxt = falseif you want Colly to respectrobots.txt; check the default for your version. - Use
MaxDepthandAllowedDomainsso a crawl stays where you intended. - Log status codes from
OnError; a growing number of 429s means slow down.
Common questions
Why does my async Colly program exit without results?
Most often c.Wait() is missing. In async mode Visit returns at once, and Wait blocks until all requests finish.
Do 404 and 403 responses reach OnHTML?
No. Colly sends status 400 and above to OnError. Set ParseHTTPErrorResponse to true if you need to parse error pages.
How do I limit requests per site in Colly?
Add a LimitRule with a DomainGlob, a low Parallelism and a Delay or RandomDelay.
Is it safe to append to a slice from OnHTML?
Not in async mode. Send results to a channel or protect the slice with a mutex.
How do I add a cookie from a solved challenge?
Call c.SetCookies with the page URL and an http.Cookie, then retry the request; the collector's jar sends it from then on.
Keep reading
- CollyThe Go scraping framework built around a collector with callbacks, known for speed, low memory use and easy parallelism.
- Solve AWS WAF CAPTCHA in GoDetect the AWS WAF puzzle from Go, place the aws-waf-token cookie in a cookiejar and repeat the request transparently.
- Rate limitingCaps on requests per IP, key or session, the 429 response that enforces them, and the limit GateSolver applies to its own API.
- Solve reCAPTCHA v2 in GoA typed Go client for reCAPTCHA v2: request and response structs, net/http calls and a ticker bounded by a context deadline.