Colly是golang的一个爬虫框架, 从简单的爬虫到处理数百万页面的异步爬虫都可以适用。
Colly安装:
go get -u github.com/gocolly/colly
基本使用:
package main
import (
"fmt" "github.com/gocolly/colly"
)
func main() {
// 初始化一个默认的Collector
c := colly.NewCollector(
// 限定爬取网址的域名
colly.AllowedDomains("hackerspaces.org", "wiki.hackerspaces.org"),
)
// 在成功返回页面html后匹配页面上的元素,进行处理(使用像jquery的元素查询方式)
c.OnHTML("a[href]", func(e *colly.HTMLElement) {
link := e.Attr("href")
// 访问下一条链接
c.Visit(e.Request.AbsoluteURL(link))
})
// request请求前的调用,可以修改一些请求的参数,或者输出些什么
c.OnRequest(func(r *colly.Request) {
fmt.Println("Visiting", r.URL.String())
})
// 开始抓取, 入口链接
c.Visit("https://hackerspaces.org/")
}