Golang爬蟲框架 colly的使用
Golang爬蟲框架 colly 簡介
colly是一個采用Go語言編寫的Web爬蟲框架,旨在提供一個能夠些任何爬蟲/采集器/蜘蛛的簡介模板,通過Colly。你可以輕松的從網(wǎng)站提取結(jié)構(gòu)化數(shù)據(jù),然后進(jìn)行數(shù)據(jù)挖掘,處理或歸檔
項目特性
- 清晰明了的API
- 速度快(每個內(nèi)核上的請求數(shù)大于1K)
- 管理每個域的請求延遲和最大并發(fā)數(shù)
- 自動cookie和會話處理
- 同步/異步/ 并行抓取
- 高速緩存
- 自動處理非Unicode編碼
- 支持Robots.txt
- 支持Google App Engine
- 通過環(huán)境變量進(jìn)行配置
- 可拓展
安裝colly
go get -u github.com/gocolly/colly
第一個colly 應(yīng)用
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/") }
回調(diào)函數(shù)的調(diào)用順序
- OnRequest 在請求之前調(diào)用
- OnError 如果請求期間發(fā)生錯誤,則調(diào)用
- OnResponseHeaders 在收到響應(yīng)標(biāo)頭后調(diào)用
- OnResponse 收到回復(fù)后調(diào)用
- OnHTML OnResponse如果接收到的內(nèi)容是HTML ,則在此之后立即調(diào)用
- OnXML OnHTML如果接收到的內(nèi)容是HTML或XML ,則在之后調(diào)用
- OnScraped 在OnXML回調(diào)之后調(diào)用
實例
func collback() { // 添加回調(diào) 收集器 c:= colly.NewCollector() c.OnRequest(func(r *colly.Request) { fmt.Println("請求前調(diào)用:OnRequest") // fmt.Println("Visiting", r.URL) }) c.OnError(func(_ *colly.Response, err error) { fmt.Println("發(fā)生錯誤調(diào)用:OnReOnError") //log.Println("Something went wrong:", err) }) /* c.OnResponseHeaders(func(r *colly.Response) { //高版本已經(jīng)不用了 fmt.Println("Visited", r.Request.URL) }) */ c.OnResponse(func(r *colly.Response) { fmt.Println("獲得響應(yīng)后調(diào)用:OnResponse") //fmt.Println("Visited", r.Request.URL) }) c.OnHTML("a[href]", func(e *colly.HTMLElement) { fmt.Println("OnResponse收到html內(nèi)容后調(diào)用: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內(nèi)容后調(diào)用:OnXML") //fmt.Println(e.Text) }) c.OnScraped(func(r *colly.Response) { fmt.Println("結(jié)束", r.Request.URL) }) c.Visit("https://gorm.io/zh_CN/docs/") }
得到的:
colly 的配置
設(shè)置UserAgent
//設(shè)置UserAgent的兩種方式: /* //方式一 : c2 := colly.NewCollector() c2.UserAgent = "xy" c2.AllowURLRevisit = true*/ /* //方式二 : c2 := colly.NewCollector( colly.UserAgent("xy"), colly.AllowURLRevisit(), )*/
設(shè)置Cookie
//設(shè)置cookie的兩種方式 //方式一:通過手動網(wǎng)頁添加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的默認(rèn)http客戶端作為網(wǎng)絡(luò)層。可以通過更改默認(rèn)的HTTP roundtripper來調(diào)整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
回調(diào)方法
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元素結(jié)構(gòu)如下:
colly框架重構(gòu)爬蟲
package main import ( "fmt" "github.com/gocolly/colly" ) func main() { c:= colly.NewCollector() c.OnHTML(".sidebar_link", func(e *colly.HTMLElement) { // 左側(cè)鏈接 href := e.Attr("href") if href != "index.html"{ c.Visit(e.Request.AbsoluteURL(href)) } }) c.OnHTML(".article-title", func(h *colly.HTMLElement) { // 選擇鏈接之后的標(biāo)題 title := h.Text fmt.Printf("title: %v\n",title) }) c.OnHTML(".article", func(h *colly.HTMLElement) { //內(nèi)容 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/") }
到此這篇關(guān)于Golang爬蟲框架 colly的使用的文章就介紹到這了,更多相關(guān)Golang colly內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
golang 實現(xiàn)時間戳和時間的轉(zhuǎn)化
這篇文章主要介紹了golang 實現(xiàn)時間戳和時間的轉(zhuǎn)化操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-05-05教你用go語言實現(xiàn)比特幣交易功能(Transaction)
每一筆比特幣交易都會創(chuàng)造輸出,輸出都會被區(qū)塊鏈記錄下來。給某個人發(fā)送比特幣,實際上意味著創(chuàng)造新的 UTXO 并注冊到那個人的地址,可以為他所用,今天通過本文給大家分享go語言實現(xiàn)比特幣交易功能,一起看看吧2021-05-05Golang 實現(xiàn)Socket服務(wù)端和客戶端使用TCP協(xié)議通訊
這篇文章主要介紹了Golang 實現(xiàn)Socket服務(wù)端和客戶端使用TCP協(xié)議通訊,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-12-12一文帶你了解Golang中interface的設(shè)計與實現(xiàn)
本文就來詳細(xì)說說為什么說?接口本質(zhì)是一種自定義類型,以及這種自定義類型是如何構(gòu)建起?go?的?interface?系統(tǒng)的,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-01-01Go語言基于HTTP的內(nèi)存緩存服務(wù)的實現(xiàn)
這篇文章主要介紹了Go語言基于HTTP的內(nèi)存緩存服務(wù),本程序采用REST接口,支持設(shè)置(Set)、獲取(Get)和刪除(Del)這3個基本操作,同時還支持對緩存服務(wù)狀態(tài)進(jìn)行查詢,需要的朋友可以參考下2022-08-08