gocolly是用go實現的網絡爬蟲框架,目前在github上具有3400+星,名列go版爬蟲程序榜首。gocolly快速優雅,在單核上每秒可以發起1K以上請求;以回調函數的形式提供了一組接口,可以實現任意類型的爬蟲;依賴goquery庫可以像jquery一樣選擇web元素。

gocolly的官方網站是http://go-colly.org/,提供了詳細的文檔和示例代碼。安裝colly:

go get -u github.com/gocolly/colly/...

在代碼中導入包:

import "github.com/gocolly/colly"

colly的主體是Collector對象,管理網絡通信和負責在作業運行時執行附加的回掉函數。使用colly需要先初始化Collector:

c := colly.NewCollector()

可以向colly附加各種不同類型的回掉函數,來控制收集作業或獲取信息。增加回掉函數:

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.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.OnScraped(func(r *colly.Response) {
    fmt.Println("Finished", r.URL) 
})

回掉函數的調用順序如下:

  • OnRequest 在發起請求前被調用
  • OnError 請求過程中如果發生錯誤被調用
  • OnResponse 收到回覆後被調用
  • OnHTML 在OnResponse之後被調用,如果收到的內容是HTML
  • OnScraped 在OnHTML之後被調用

官方提供的Basic示例代碼:

package main

import (
    "fmt"
    "github.com/gocolly/colly"
)
func main() {
    // Instantiate default collector
    c := colly.NewCollector()
    // Visit only domains: hackerspaces.org, wiki.hackerspaces.org
    c.AllowedDomains = []string{"hackerspaces.org", "wiki.hackerspaces.org"}
    // On every a element which has href attribute call callback
    c.OnHTML("a[href]", func(e *colly.HTMLElement) {
        link := e.Attr("href")
        // Print link
        fmt.Printf("Link found: %q -> %s\n", e.Text, link)
        // Visit link found on page
        // Only those links are visited which are in AllowedDomains
        c.Visit(e.Request.AbsoluteURL(link))
    })
    // Before making a request print "Visiting ..."
    c.OnRequest(func(r *colly.Request) {
        fmt.Println("Visiting", r.URL.String())
    })
    // Start scraping on https://hackerspaces.org
    c.Visit("https://hackerspaces.org/")
}

該實例程序僅訪問hackerspaces.org域內的鏈接,OnHTML回掉函數的選擇器為a[href],選擇頁面內具有href屬性的a類型元素,找到鏈接後繼續抓取。 運行的部分結果如下:

PS E:\mygo\src\github.com\gocolly\colly\_examples\basic> .\basic.exe

Visiting https://hackerspaces.org/

Link found: "navigation" -> #column-one

Link found: "search" -> #searchInput

Link found: "" -> /File:Cbase07.jpg

Visiting https://hackerspaces.org/File:Cbase07.jpg

Link found: "navigation" -> #column-one

Link found: "search" -> #searchInput

Link found: "File" -> #file

Link found: "File history" -> #filehistory

Link found: "File usage" -> #filelinks

Link found: "" -> /images/e/ec/Cbase07.jpg

Visiting https://hackerspaces.org/images/e/ec/Cbase07.jpg

Link found: "800 × 600 pixels" -> /images/thumb/e/ec/Cbase07.jpg/800px-Cbase07.jpg

Visiting https://hackerspaces.org/images/thumb/e/ec/Cbase07.jpg/800px-Cbase07.jpg