Golang 網絡爬蟲框架gocolly/colly

gocolly是Golang實現的網絡爬蟲框架,名列go版爬蟲程序榜首。

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

例子
import ( "fmt" "github.com/gocolly/colly")func main() { c := colly.NewCollector() c.OnResponse(func(r *colly.Response) { fmt.Println("IP:", string(r.Body)) }) //c.SetProxy("http://127.0.0.1:1080") c.Visit("http://ip.cip.cc/")}

SetProxy函數可以用來配置HTTP代理。

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

c := colly.NewCollector()

vgo
vgo是Go語言推出的第三方庫管理工具,在Go語言新版本中使用。

常用的命令行:
· go help mod 查看幫助。

· go mod init <項目模塊名稱>初始化模塊,會在項目根目錄下生成 go.mod 文件,是可以自己手動編輯的。

依賴包大多在Github上,安裝依賴可能會出現連接超時等問題,可以配置全局git代理:

git config --global http.proxy http://127.0.0.1:1080git config --global https.proxy https://127.0.0.1:1080#取消代理:git config --global --unset http.proxygit config --global --unset https.proxy

cmd走shadowsocks代理:

set http_proxy=127.0.0.1:1080set https_proxy=127.0.0.1:1080curl cip.ccIP : 140.206.97.42地址 : 中國 上海數據二 : 上海市 | 聯通URL : http://www.cip.cc/140.206.97.42

Linux使用export設置環境變量,代碼同上。

回掉函數的調用順序

  1. OnRequest 在發起請求前被調用。

  2. OnError 請求過程中如果發生錯誤被調用。

  3. OnResponse 收到回覆後被調用。

  4. OnHTML 在OnResponse之後被調用,如果收到的內容是HTML 。

  5. OnScraped 在OnHTML之後被調用。

官方提供的Basic示例代碼:

package mainimport ( "fmt" "github.com/gocolly/colly")func main() { // Instantiate default collector c := colly.NewCollector( // Visit only domains: hackerspaces.org, wiki.hackerspaces.org colly.AllowedDomains("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類型元素,找到鏈接後繼續抓取。 運行的部分結果如下:

Visiting https://hackerspaces.org/Link found: "navigation" -> #column-oneLink found: "search" -> #searchInputLink found: "" -> /File:Cbase07.jpgVisiting https://hackerspaces.org/File:Cbase07.jpgLink found: "navigation" -> #column-oneLink found: "search" -> #searchInputLink found: "File" -> #fileLink found: "File history" -> #filehistoryLink found: "File usage" -> #filelinksLink found: "" -> /images/e/ec/Cbase07.jpgVisiting https://hackerspaces.org/images/e/ec/Cbase07.jpgLink found: "800 × 600 pixels" -> /images/thumb/e/ec/Cbase07.jpg/800px-Cbase07.jpgVisiting https://hackerspaces.org/images/thumb/e/ec/Cbase07.jpg/800px-Cbase07.jpg

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章