1. 程式人生 > >go語言解析網頁利器goquery使用教程(爬蟲必備)

go語言解析網頁利器goquery使用教程(爬蟲必備)

爬蟲 導入 log 說明 常見 png eba 選擇器 我們

某些時候需要爬取網頁中指定信息時,通常需要一些框架解析網頁行成dom模型,然後來操作節點來獲取相應的信息。在java中很顯然就是Jsoup,而在Golang裏,應該就是這個goquery了吧。

goquery github地址 https://github.com/PuerkitoBio/goquery

安裝

由於它依賴 Go語言的 net/html 包以及css選擇庫 cascadia, 因此我們要先手動安裝net/html包,後者不需要我們手動安裝。
運行

go get https://github.com/PuerkitoBio/goquery

之後可能會出現golang.org\x失敗相關的,那裏是由於被墻了導致(好像又不是o_o ....),那裏自己百度下吧,具體錯誤我當時也沒記錄( ̄、 ̄)

然後應該就可以使用goquery包了

使用

語法相關這裏就不過分說明,直接上用法吧(●‘?‘●)

首先導入該包

import  "github.com/PuerkitoBio/goquery"

加載頁面

就用官方的例子吧,我比較懶??

  // 請求html頁面
  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)
  }

獲得document對象

有多種獲得document對象的方法,這裏是比較常見的一種

  // 加載 HTML document對象
  doc, err := goquery.NewDocumentFromReader(res.Body)
  if err != nil {
    log.Fatal(err)
  }

選擇元素

選擇器語法就是css選擇器語法,和jsoup中的類似

  // 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)
  })

要爬取的即是圖中的內容

技術分享圖片

運行結果

技術分享圖片

go語言解析網頁利器goquery使用教程(爬蟲必備)