-->

go语言解析网页利器goquery使用教程(爬虫必备)

某些时候需要爬取网页中指定信息时,通常需要一些框架解析网页行成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)
  })

要爬取的即是图中的内容

运行结果

posted @ 2018-12-23 11:43  Asche  阅读(5852)  评论(0编辑  收藏  举报