ProxyForge Download

Colly Web Scraping in Go with Proxy Rotation

Colly Web Scraping in Go with Proxy Rotation

Web scraping is a common task for developers, and when you need to scale your operations, managing proxies becomes crucial. Go, with its performance and concurrency model, is an excellent choice for building robust web scrapers. Colly, a popular Go library similar to Scrapy for Python, simplifies the process of setting up web crawlers with features like proxy rotation, rate limiting, and distributed crawling.

In this guide, we'll explore how to set up a Colly spider in Go that rotates proxies using built-in and custom proxy switchers. We'll also cover how to implement error handling, manage rate limits, and extend the scraper for distributed crawling using Redis. Finally, I’ll touch on how ProxyForge can simplify your proxy management process.

Introduction

Colly is a high-performance web scraping framework for Go that provides features like queue management, deduplication, rate limiting, and cookie handling out of the box. It's particularly well-suited for large-scale scraping projects due to its efficient use of goroutines and channels.

To get started with Colly, you need to have Go installed on your machine. You can install Colly by running:

go get -u github.com/gocolly/colly/v2

Setting Up a Basic Colly Spider

Before diving into proxy rotation, let's set up a basic Colly spider that scrapes product data from an example website.

package main

import (
    "fmt"
    "github.com/gocolly/colly/v2"
)

func main() {
    // Create a new collector
    c := colly.NewCollector(
        colly.AllowedDomains("example.com"),
    )

    // Define the callback for product data extraction
    c.OnHTML(".product", func(e *colly.HTMLElement) {
        name := e.ChildText(".name")
        price := e.ChildText(".price")
        fmt.Printf("Product: %s, Price: %s\n", name, price)
    })

    // Start the scraping process
    c.Visit("https://example.com/products")
}

This script sets up a collector that visits a specific URL and extracts product names and prices from elements with the classes .product, .name, and .price.

Proxy Rotation with Colly

Colly provides built-in support for proxy rotation using the SetProxyFunc method. You can use a round-robin proxy switcher to cycle through a list of proxies.

Built-in Round-Robin Proxy Switcher

package main

import (
    "fmt"
    "github.com/gocolly/colly/v2"
)

func main() {
    // Create a new collector
    c := colly.NewCollector(
        colly.AllowedDomains("example.com"),
    )

    // Set up proxy rotation
    c.SetProxyFunc(colly.RoundRobinProxySwitcher("http://p1:8080", "http://p2:8080"))

    // Define the callback for product data extraction
    c.OnHTML(".product", func(e *colly.HTMLElement) {
        name := e.ChildText(".name")
        price := e.ChildText(".price")
        fmt.Printf("Product: %s, Price: %s\n", name, price)
    })

    // Start the scraping process
    c.Visit("https://example.com/products")
}

The RoundRobinProxySwitcher function takes a list of proxy URLs and rotates through them for each request.

Custom Proxy Switcher

If you need more control over the proxy selection, such as implementing weighted or sticky sessions, you can define a custom proxy switcher function:

package main

import (
    "fmt"
    "net/url"
    "github.com/gocolly/colly/v2"
)

func customProxySwitcher(r *http.Request) (*url.URL, error) {
    // Implement your logic here
    return url.Parse("http://p1:8080")
}

func main() {
    // Create a new collector
    c := colly.NewCollector(
        colly.AllowedDomains("example.com"),
    )

    // Set up custom proxy switcher
    c.SetProxyFunc(customProxySwitcher)

    // Define the callback for product data extraction
    c.OnHTML(".product", func(e *colly.HTMLElement) {
        name := e.ChildText(".name")
        price := e.ChildText(".price")
        fmt.Printf("Product: %s, Price: %s\n", name, price)
    })

    // Start the scraping process
    c.Visit("https://example.com/products")
}

In this example, customProxySwitcher is a placeholder for your logic to select proxies based on specific criteria.

SOCKS5 Proxies

Colly also supports SOCKS5 proxies:

package main

import (
    "fmt"
    "github.com/gocolly/colly/v2"
)

func main() {
    // Create a new collector
    c := colly.NewCollector(
        colly.AllowedDomains("example.com"),
    )

    // Set up SOCKS5 proxy rotation
    c.SetProxyFunc(colly.RoundRobinProxySwitcher("socks5://host1:port", "socks5://host2:port"))

    // Define the callback for product data extraction
    c.OnHTML(".product", func(e *colly.HTMLElement) {
        name := e.ChildText(".name")
        price := e.ChildText(".price")
        fmt.Printf("Product: %s, Price: %s\n", name, price)
    })

    // Start the scraping process
    c.Visit("https://example.com/products")
}

Rate Limiting

To avoid overwhelming the target website, you can set up rate limits using LimitRule:

package main

import (
    "fmt"
    "time"
    "github.com/gocolly/colly/v2"
)

func main() {
    // Create a new collector
    c := colly.NewCollector(
        colly.AllowedDomains("example.com"),
    )

    // Set up rate limiting
    c.Limit(&colly.LimitRule{
        DomainGlob: "*",
        Parallelism: 4,
        Delay:       2 * time.Second,
    })

    // Define the callback for product data extraction
    c.OnHTML(".product", func(e *colly.HTMLElement) {
        name := e.ChildText(".name")
        price := e.ChildText(".price")
        fmt.Printf("Product: %s, Price: %s\n", name, price)
    })

    // Start the scraping process
    c.Visit("https://example.com/products")
}

This setup limits the number of concurrent requests to 4 and adds a delay of 2 seconds between requests for each domain.

Error Handling

Error handling in Colly is done through the OnError callback:

package main

import (
    "fmt"
    "github.com/gocolly/colly/v2"
)

func main() {
    // Create a new collector
    c := colly.NewCollector(
        colly.AllowedDomains("example.com"),
    )

    // Define the error handling callback
    c.OnError(func(r *colly.Response, err error) {
        if r.StatusCode >= 400 && r.StatusCode < 500 {
            fmt.Printf("Client error: %d - %s\n", r.StatusCode, err)
        } else {
            fmt.Printf("Server error or network issue: %d - %s\n", r.StatusCode, err)
        }
    })

    // Define the callback for product data extraction
    c.OnHTML(".product", func(e *colly.HTMLElement) {
        name := e.ChildText(".name")
        price := e.ChildText(".price")
        fmt.Printf("Product: %s, Price: %s\n", name, price)
    })

    // Start the scraping process
    c.Visit("https://example.com/products")
}

This callback checks the response status code to determine if it's a client error (4xx), a server error (5xx), or a network issue.

Distributed Crawling with Redis

For large-scale scraping, you can distribute your crawler across multiple machines using Redis as a queue backend:

package main

import (
    "fmt"
    "github.com/gocolly/colly/v2"
    "github.com/gocolly/colly/v2/storage/redisstore"
)

func main() {
    // Create a new collector
    c := colly.NewCollector(
        colly.AllowedDomains("example.com"),
    )

    // Set up Redis storage for distributed crawling
    redisStore, _ := redisstore.New("localhost:6379")
    c.SetStorage(redisStore)

    // Define the callback for product data extraction
    c.OnHTML(".product", func(e *colly.HTMLElement) {
        name := e.ChildText(".name")
        price := e.ChildText(".price")
        fmt.Printf("Product: %s, Price: %s\n", name, price)
    })

    // Start the scraping process
    c.Visit("https://example.com/products")
}

This setup uses Redis to store and manage the request queue across multiple instances of your crawler.

Async Mode

To enable asynchronous mode in Colly, set c.Async = true:

Free proxies break. ProxyForge doesn't.

The free lists above are public and often unreliable. ProxyForge auto-tests and rotates proxies on your machine, your IP — no stale lists, no shared pools, no surprises. One-off purchase, no subscription.

Download ProxyForge free →