【GO】21.goquery html页面分析golang库

  • 下载包:

go get github.com/PuerkitoBio/goquery

 

  • 示例代码:

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

你没看错,就是把https://github.com/PuerkitoBio/goquery的示例代码copy了过来,偷个懒

 

  • 常用方法:

//返回标签的内容
selection.Find("span.lab-round").First().Text()

//返回标签内的html
selection.Find("span.lab-round").First().Html()

//返回标签内的属性
selection.Find("span.lab-round").First().Attr("href")

Find方法内选择器跟JQuery的一样,ID选择器、类选择器、标签选择器等等,参考JQuery或下面的页面链接

 

  • 参考页面

https://cloud.tencent.com/developer/article/1196783

https://tomoya92.github.io/2017/06/21/golang-goquery/

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值