快速上手

2020-07-27 19:55 更新

使用colly之前請確保已經按照上一節(jié)配置好開發(fā)環(huán)境。 下面通過一些簡單的例子,帶你快速上手colly。

首先,你需要在代碼中引入colly包:

import "github.com/gocolly/colly"

接下來介紹colly中幾個關鍵概念:

Collector

Colly的首要入口是一個 Collector 對象。 Collector 管理網絡通信并負責在 Collector job 運行時執(zhí)行附加的回調。使用colly,你必須初始化一個Collector:

c := colly.NewCollector()

為 Collector 添加回調函數

回調 你可以把不同類型的回調函數附加到收集器上來控制收集任務,然后取回信息

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)
})

回調函數的執(zhí)行順序

  1. OnRequest 請求發(fā)出之前調用

  1. OnError 請求過程中出現Error時調用

  1. OnResponse 收到response后調用

  1. OnHTML 如果收到的內容是HTML,就在onResponse執(zhí)行后調用

  1. OnXML 如果收到的內容是HTML或者XML,就在onHTML執(zhí)行后調用

  1. OnScraped OnXML執(zhí)行后調用
以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號