Golang爬蟲框架 colly的使用
Golang爬蟲框架 colly 簡介
colly是一個采用Go語言編寫的Web爬蟲框架,旨在提供一個能夠些任何爬蟲/采集器/蜘蛛的簡介模板,通過Colly。你可以輕松的從網站提取結構化數(shù)據(jù),然后進行數(shù)據(jù)挖掘,處理或歸檔
項目特性
- 清晰明了的API
- 速度快(每個內核上的請求數(shù)大于1K)
- 管理每個域的請求延遲和最大并發(fā)數(shù)
- 自動cookie和會話處理
- 同步/異步/ 并行抓取
- 高速緩存
- 自動處理非Unicode編碼
- 支持Robots.txt
- 支持Google App Engine
- 通過環(huán)境變量進行配置
- 可拓展
安裝colly
go get -u github.com/gocolly/colly
第一個colly 應用
package main import ( "fmt" "github.com/gocolly/colly" ) func main() { c := colly.NewCollector() // goquery selector class c.OnHTML(".sidebar_link", func(e *colly.HTMLElement) { e.Request.Visit(e.Attr("href")) /* 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))*/ }) c.OnRequest(func(r *colly.Request) { fmt.Println("url:",r.URL) }) c.Visit("https://gorm.io/zh_CN/docs/") }
回調函數(shù)的調用順序
- OnRequest 在請求之前調用
- OnError 如果請求期間發(fā)生錯誤,則調用
- OnResponseHeaders 在收到響應標頭后調用
- OnResponse 收到回復后調用
- OnHTML OnResponse如果接收到的內容是HTML ,則在此之后立即調用
- OnXML OnHTML如果接收到的內容是HTML或XML ,則在之后調用
- OnScraped 在OnXML回調之后調用
實例
func collback() { // 添加回調 收集器 c:= colly.NewCollector() c.OnRequest(func(r *colly.Request) { fmt.Println("請求前調用:OnRequest") // fmt.Println("Visiting", r.URL) }) c.OnError(func(_ *colly.Response, err error) { fmt.Println("發(fā)生錯誤調用:OnReOnError") //log.Println("Something went wrong:", err) }) /* c.OnResponseHeaders(func(r *colly.Response) { //高版本已經不用了 fmt.Println("Visited", r.Request.URL) }) */ c.OnResponse(func(r *colly.Response) { fmt.Println("獲得響應后調用:OnResponse") //fmt.Println("Visited", r.Request.URL) }) c.OnHTML("a[href]", func(e *colly.HTMLElement) { fmt.Println("OnResponse收到html內容后調用:OnHTML") //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("OnResponse收到xml內容后調用:OnXML") //fmt.Println(e.Text) }) c.OnScraped(func(r *colly.Response) { fmt.Println("結束", r.Request.URL) }) c.Visit("https://gorm.io/zh_CN/docs/") }
得到的:
colly 的配置
設置UserAgent
//設置UserAgent的兩種方式: /* //方式一 : c2 := colly.NewCollector() c2.UserAgent = "xy" c2.AllowURLRevisit = true*/ /* //方式二 : c2 := colly.NewCollector( colly.UserAgent("xy"), colly.AllowURLRevisit(), )*/
設置Cookie
//設置cookie的兩種方式 //方式一:通過手動網頁添加cookies c.OnRequest(func(r *colly.Request) { r.Headers.Add("cookie","_ga=GA1.2.1611472128.1650815524; _gid=GA1.2.2080811677.1652022429; __atuvc=2|17,0|18,5|19") }) // 方式二 :通過url 添加cookies siteCookie := c.Cookies("url") c.SetCookies("",siteCookie)
HTTP配置
Colly使用Golang的默認http客戶端作為網絡層??梢酝ㄟ^更改默認的HTTP roundtripper來調整HTTP選項。
c := colly.NewCollector() c.WithTransport(&http.Transport{ Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, DualStack: true, }).DialContext, MaxIdleConns: 100, IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, }
colly頁面爬取和解析
頁面爬取和解析重點方法是 onHTML
回調方法
c.OnHTML("a[href]", func(e *colly.HTMLElement) { fmt.Printf("e.Name:%v\n",e.Name) e.Request.Visit(e.Attr("href")) }) func html() { c:= colly.NewCollector() c.OnHTML("#sidebar", func(e *colly.HTMLElement) { //fmt.Printf("e.Name:%v\n",e.Name) //名字 //fmt.Printf("e.Text:%v\n",e.Text) //文本 ret, _ := e.DOM.Html() // selector 選擇器 fmt.Printf("ret:%v\n",ret) }) c.OnRequest(func(r *colly.Request) { fmt.Println("url:",r.URL) }) c.Visit("https://gorm.io/zh_CN/docs/") }
第一個參數(shù)是:goquery選擇器,可以元素名稱,ID或者Class選擇器,第二個參數(shù)是根據(jù)第一個選擇器獲得的HTML元素結構如下:
colly框架重構爬蟲
package main import ( "fmt" "github.com/gocolly/colly" ) func main() { c:= colly.NewCollector() c.OnHTML(".sidebar_link", func(e *colly.HTMLElement) { // 左側鏈接 href := e.Attr("href") if href != "index.html"{ c.Visit(e.Request.AbsoluteURL(href)) } }) c.OnHTML(".article-title", func(h *colly.HTMLElement) { // 選擇鏈接之后的標題 title := h.Text fmt.Printf("title: %v\n",title) }) c.OnHTML(".article", func(h *colly.HTMLElement) { //內容 content, _ := h.DOM.Html() fmt.Printf("content: %v\n",content) }) c.OnRequest(func(r *colly.Request) { fmt.Println("url:",r.URL.String()) }) c.Visit("https://gorm.io/zh_CN/docs/") }
到此這篇關于Golang爬蟲框架 colly的使用的文章就介紹到這了,更多相關Golang colly內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
教你用go語言實現(xiàn)比特幣交易功能(Transaction)
每一筆比特幣交易都會創(chuàng)造輸出,輸出都會被區(qū)塊鏈記錄下來。給某個人發(fā)送比特幣,實際上意味著創(chuàng)造新的 UTXO 并注冊到那個人的地址,可以為他所用,今天通過本文給大家分享go語言實現(xiàn)比特幣交易功能,一起看看吧2021-05-05Golang 實現(xiàn)Socket服務端和客戶端使用TCP協(xié)議通訊
這篇文章主要介紹了Golang 實現(xiàn)Socket服務端和客戶端使用TCP協(xié)議通訊,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-12-12一文帶你了解Golang中interface的設計與實現(xiàn)
本文就來詳細說說為什么說?接口本質是一種自定義類型,以及這種自定義類型是如何構建起?go?的?interface?系統(tǒng)的,感興趣的小伙伴可以跟隨小編一起學習一下2023-01-01