使用colly之前請確保已經按照上一節(jié)配置好開發(fā)環(huán)境。 下面通過一些簡單的例子,帶你快速上手colly。
首先,你需要在代碼中引入colly包:
import "github.com/gocolly/colly"
接下來介紹colly中幾個關鍵概念:
Colly的首要入口是一個 Collector 對象。 Collector 管理網絡通信并負責在 Collector job 運行時執(zhí)行附加的回調。使用colly,你必須初始化一個Collector:
c := colly.NewCollector()
回調 你可以把不同類型的回調函數附加到收集器上來控制收集任務,然后取回信息
c.OnRequest(func(r *colly.Request) {
fmt.Println("Visiting", r.URL)
})
c.OnError(func(_ *colly.Response, err error) {
log.Println("Something went wrong:", err)
})
c.OnResponse(func(r *colly.Response) {
fmt.Println("Visited", r.Request.URL)
})
c.OnHTML("a[href]", func(e *colly.HTMLElement) {
e.Request.Visit(e.Attr("href"))
})
c.OnHTML("tr td:nth-of-type(1)", func(e *colly.HTMLElement) {
fmt.Println("First column of a table row:", e.Text)
})
c.OnXML("http://h1", func(e *colly.XMLElement) {
fmt.Println(e.Text)
})
c.OnScraped(func(r *colly.Response) {
fmt.Println("Finished", r.Request.URL)
})
onResponse
執(zhí)行后調用onHTML
執(zhí)行后調用OnXML
執(zhí)行后調用
更多建議: