gocolly是用go实现的网络爬虫框架,目前在github上具有8600+星,名列go版爬虫程序榜首。gocolly快速优雅,在单核上每秒可以发起1K以上请求;以回调函数的形式提供了一组接口,可以实现任意类型的爬虫;依赖goquery库可以像jquery一样选择web元素。

gocolly的官方网站是 http://go-colly.org/,提供了详细的文档和示例代码。

go get -u github.com/gocolly/colly
import "github.com/gocolly/colly"

colly的主体是Collector对象,管理网络通信和负责在作业运行时执行附加的回掉函数。

colly.NewCollector()

可以向colly附加各种不同类型的回掉函数,来控制收集作业或获取信息。

回掉函数的调用顺序如下:

OnRequest
OnError
OnResponse
OnHTML
OnScraped

官方提供的Basic示例代码:

func main() {
    c := colly.NewCollector()

    // Find and visit all links
    c.OnHTML("a", func(e *colly.HTMLElement) {
        e.Request.Visit(e.Attr("href"))
    })

    c.OnRequest(func(r *colly.Request) {
        fmt.Println("Visiting", r.URL)
    })

    c.Visit("http://go-colly.org/")
}

ECHO:

Visiting http://go-colly.org/
Visiting http://go-colly.org/docs/
Visiting http://go-colly.org/articles/
Visiting http://go-colly.org/services/
Visiting http://go-colly.org/datasets/
Visiting https://godoc.org/github.com/gocolly/colly
Visiting https://godoc.org/
Visiting https://godoc.org/-/about
Visiting https://golang.org/