Colly 是一个用于构建网络爬虫的 Golang 框架。使用 Colly,您可以构建各种复杂的网络爬虫,从简单的爬虫到处理数百万网页的复杂异步网站爬虫。 Colly 提供了一个 API 用于执行网络请求和处理接收到的内容(例如与 HTML 文档的 DOM 树交互)
package main
import (
"fmt"
"github.com/gocolly/colly"
)
func main () {
//实例化colly对象,这里配置了只允许爬取hackerspaces.org
c := colly NewCollector (
// Visit only domains: hackerspaces.org, wiki.hackerspaces.org
colly.AllowedDomains ( "hackerspaces.org" ),
)
// On every a element which has href attribute call callback
c.OnHTML("a[href]" , func ( e * colly.HTMLElement ) {
link := e.Attr("href")
// Print link
fmt.Printf("Link found: %q -> %s\n" , e.Text, link )
// Visit link found on page
// Only those links are visited which are in AllowedDomains
c.Visit( e.Request.AbsoluteURL(link))
})
// Before making a request print "Visiting ..."
c.OnRequest( func ( r *colly.Request ) {
fmt.Println( "Visiting" , r.URL.String())
})
// Start scraping on https://hackerspaces.org
c.Visit("https://hackerspaces.org/")
}
colly的性能非常好,配置参数可以参考 colly配置
go-colly, golang,爬虫