用 Go 做爬蟲的話,有哪些庫可以選擇?
關注公眾號 “轉(zhuǎn)角遇到GitHub” ,每天推薦給你優(yōu)秀開源項目
說起爬蟲,很多人可能想到 Python,其實 Go 目前在這方面表現(xiàn)也還可以。今天看看 Go 比較有名的爬蟲相關庫有哪些?
GoQuery
說起 Go 爬蟲相關庫,最早、最知名的應該是 goquery,這是模仿 jquery 的,所以使用過 jquery 的,用 goquery 會特別親切,功能也很強大。
項目地址:https://github.com/PuerkitoBio/goquery,Star 數(shù) 9.4k+。
例子:
package?main
import?(
??"fmt"
??"log"
??"net/http"
??"github.com/PuerkitoBio/goquery"
)
func?ExampleScrape()?{
??//?Request?the?HTML?page.
??res,?err?:=?http.Get("http://metalsucks.net")
??if?err?!=?nil?{
????log.Fatal(err)
??}
??defer?res.Body.Close()
??if?res.StatusCode?!=?200?{
????log.Fatalf("status?code?error:?%d?%s",?res.StatusCode,?res.Status)
??}
??//?Load?the?HTML?document
??doc,?err?:=?goquery.NewDocumentFromReader(res.Body)
??if?err?!=?nil?{
????log.Fatal(err)
??}
??//?Find?the?review?items
??doc.Find(".sidebar-reviews?article?.content-block").Each(func(i?int,?s?*goquery.Selection)?{
????//?For?each?item?found,?get?the?band?and?title
????band?:=?s.Find("a").Text()
????title?:=?s.Find("i").Text()
????fmt.Printf("Review?%d:?%s?-?%s\n",?i,?band,?title)
??})
}
func?main()?{
??ExampleScrape()
}
colly
相對來說 goquery API 有些低級,而 colly 這個庫是一個真正的爬蟲框架。這是一個用于 Golang 的優(yōu)雅的 Scraper 和 Crawler 框架。
項目地址:https://github.com/gocolly/colly,Star 數(shù):12.3k+。
它還有一個專門的網(wǎng)站:https://go-colly.org。
func?main()?{
?c?:=?colly.NewCollector()
?//?Find?and?visit?all?links
?c.OnHTML("a[href]",?func(e?*colly.HTMLElement)?{
??e.Request.Visit(e.Attr("href"))
?})
?c.OnRequest(func(r?*colly.Request)?{
??fmt.Println("Visiting",?r.URL)
?})
?c.Visit("http://go-colly.org/")
}
注意,colly 是基于 goquery 的。
soup
Go 中的網(wǎng)頁抓取工具,類似于 Python 的 BeautifulSoup。該庫很短小,核心代碼才 500 多行,對爬蟲實現(xiàn)感興趣的可以研究下它的源碼。
項目地址:https://github.com/anaskhan96/soup,Star 數(shù):1.4k+。
示例:
package?main
import?(
?"fmt"
?"github.com/anaskhan96/soup"
?"os"
)
func?main()?{
?resp,?err?:=?soup.Get("https://xkcd.com")
?if?err?!=?nil?{
??os.Exit(1)
?}
?doc?:=?soup.HTMLParse(resp)
?links?:=?doc.Find("div",?"id",?"comicLinks").FindAll("a")
?for?_,?link?:=?range?links?{
??fmt.Println(link.Text(),?"|?Link?:",?link.Attrs()["href"])
?}
}
Pholcus
這是國人寫的,分布式高并發(fā)爬蟲軟件。這是一個完整的項目,而不是一個庫。它支持單機、服務端、客戶端三種運行模式,擁有 Web、GUI、命令行三種操作界面;規(guī)則簡單靈活、批量任務并發(fā)、輸出方式豐富(mysql/mongodb/kafka/csv/excel等);另外它還支持橫縱向兩種抓取模式,支持模擬登錄和任務暫停、取消等一系列高級功能。
項目地址:https://github.com/henrylee2cn/pholcus,Star 數(shù) 6.6k+。
小結(jié)
以上有各自的優(yōu)劣,如果你有需求,可以根據(jù)需要選擇一個適合你的。你還知道哪些?歡迎留言
文末「閱讀原文」可直達項目首頁。
今天的項目大家覺得怎么樣嗎?如果你喜歡,請在文章底部留言、點贊或關注轉(zhuǎn)發(fā),你的支持就是我持續(xù)更新的最大動力!
推薦閱讀
轉(zhuǎn)角遇到GitHub - 送給愛開源的你
Git ·?GitHub · GitLab · Gitee
