安装goquery
GoQuery是Go语言的一个HTML解析器,类似于Python中的BeautifulSoup。它使用Go的强类型和高效性能来处理HTML,CSS和JavaScript。使用GoQuery可以轻松地从HTML文档中提取数据,例如标题,链接,表单和表格等。GoQuery还提供了强大的CSS选择器,可以让您轻松地从文档中选择元素。
go get github.com/PuerkitoBio/goquery
Go代码中导入GoQuery:
import "github.com/PuerkitoBio/goquery"
package main
import (
"fmt"
"net/http"
"github.com/PuerkitoBio/goquery"
)
func main() {
//使用http.Get方法来获取网页内容 使用我以前经常逛的phpstudy官网
resp, err := http.Get("https://www.xp.cn/using.html")
if err != nil {
fmt.Println(err)
return
}
defer resp.Body.Close()
// 读取网页内容
// body, err := ioutil.ReadAll(resp.Body)
// if err != nil {
// log.Fatal(err)
// }
// 将响应转换为UTF-8编码 (如果网站是gbk编码的)
// reader := transform.NewReader(bytes.NewReader(body), simplifiedchinese.GBK.NewDecoder())
// utf8Body, err := ioutil.ReadAll(reader)
// if err != nil {
// log.Fatal(err)
// }
// 解析网页内容
// doc, err := goquery.NewDocumentFromReader(bytes.NewReader(utf8Body))
// if err != nil {
// log.Fatal(err)
// }
// 解析网页内容
doc, err := goquery.NewDocumentFromReader(resp.Body)
if err != nil {
fmt.Println(err)
return
}
// 提取内容
doc.Find(".pb-20").Each(func(i int, s *goquery.Selection) {
title := s.Find("li div a").Text()
fmt.Printf("%s\n", title)
})
}
使用goquery包提供的NewDocumentFromReader方法来解析网页内容。然后,使用Find方法来查找网页中的标题,并输出它们。