使用colly以前,請確保您擁有最新的版本。有關詳細信息,請參閱安裝指南。git
讓咱們從一些簡單的例子開始。github
首先,你須要導入Colly到你的代碼庫:網絡
import "github.com/gocolly/colly"
Colly的主要實體是一個收集器對象。Collector管理網絡通訊,並負責在運行收集器做業時執行附加的回調。要使用colly,您必須初始化一個收集器:函數
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("//h1", func(e *colly.XMLElement) { fmt.Println(e.Text) }) c.OnScraped(func(r *colly.Response) { fmt.Println("Finished", r.Request.URL) })
1. OnRequestblog
在請求以前調用文檔
2. OnErrorget
若是請求期間發生錯誤,則調用回調函數
3.OnResponseit
收到響應後調用
4. OnHTML
若是接收到的內容是HTML,則在OnResponse以後當即調用
5. OnXML
若是接收到的內容是HTML或XML,則在OnHTML以後當即調用
6. OnScraped
在OnXML回調以後調用