学习目的
go做服务器抓取非常方便,今天我们只学习抓取网页和处理网页,后面会学习如何定时执行,包括embed嵌入模板最终打包成一个单文件.
goquery学习
库地址 “github.com/PuerkitoBio/goquery”
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
res, err := http.Get("http://www.yoby123.cn")
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)
}
doc, _ := goquery.NewDocumentFromReader(res.Body)
//两种一样
/*
body, _ := io.ReadAll(res.Body)
str:=string(body)
doc,_:=goquery.NewDocumentFromReader(strings.NewReader(str))
*/
var sc []string//且片,选择支持类 #等
doc.Find("span.cfont1").Each(func(i int,s *goquery.Selection){
sc=append(sc,s.Text())
})
str:=doc.Find("title").Text() //内容
fmt.Println(sc)
|
使用很容易,外面只需要一个Find即可,其他基本不需要,和jquery类似