基本用法
go
package main
import (
"fmt"
"github.com/gocolly/colly"
)
func main() {
// 实例化一个默认的 collector
c := colly.NewCollector(
// 访问域名 hackerspaces.org, wiki.hackerspaces.org
colly.AllowedDomains("hackerspaces.org", "wiki.hackerspaces.org"),
)
// 为每个有href 属性的元素设置回调方法
c.OnHTML("a[href]", func(e *colly.HTMLElement) {
link := e.Attr("href")
// 打印链接
fmt.Printf("Link found: %q -> %s\n", e.Text, link)
// 访问找到的链接
// 只有允许访问的链接才能被访问的到
c.Visit(e.Request.AbsoluteURL(link))
})
// 在请求前打印 "Visiting ..."
c.OnRequest(func(r *colly.Request) {
fmt.Println("Visiting", r.URL.String())
})
// 开始爬取 https://hackerspaces.org
c.Visit("https://hackerspaces.org/")
}