[转] Golang 网络爬虫框架 gocolly/colly
gocolly是用go实现的网络爬虫框架,目前在github上具有8600+星,名列go版爬虫程序榜首。gocolly快速优雅,在单核上每秒可以发起1K以上请求;以回调函数的形式提供了一组接口,可以实现任意类型的爬虫;依赖goquery库可以像jquery一样选择web元素。
gocolly的官方网站是 http://go-colly.org/,提供了详细的文档和示例代码。
安装colly: go get -u github.com/gocolly/colly
在代码中导入包:import "github.com/gocolly/colly"
colly的主体是Collector对象,管理网络通信和负责在作业运行时执行附加的回掉函数。
使用colly需要先初始化Collector:colly.NewCollector()
可以向colly附加各种不同类型的回掉函数,来控制收集作业或获取信息。
回掉函数的调用顺序如下:
1. OnRequest
在发起请求前被调用
2. OnError
请求过程中如果发生错误被调用
3. OnResponse
收到回复后被调用
4. OnHTML
在OnResponse之后被调用,如果收到的内容是HTML
5. OnScraped
在OnHTML之后被调用
官方提供的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/
报错
package google.golang.org/appengine/urlfetch: unrecognized import path "google.golang.org/appengine/urlfetch"
后请在src目录下创建一个google.golang.org
目录,然后cd到google.golang.org目录下,用git clone https://github.com/golang/appengine.git
下载