基于HTML Element 元素的选择器
使用Element名称作为选择器,如dom.Find("div")。
dom.Find("div").Each(func (i int, selection *goquery.Selection) {
fmt.Println(selection.Text())
})
ID选择器
以#加id值作为选择器
dom.Find("#id").Each(func (i int, selection *goquery.Selection) {
fmt.Println(selection.Text())
})
Class选择器
以.加class值为选择器
dom.Find(".class").Each(func (i int, selection *goquery.Selection) {
fmt.Println(selection.Text())
})
由上面的示例可以看出,goquery的选择器与jQuery的选择器用法无异,在这里就不继续赘述了,同学们可以自行探索。
常用节点属性值
Html() 获取该节点的html
dom.Find("table").Each(func (i int, selection *goquery.Selection) {
fmt.Println(selection.Html())
})
Text() 获取该节点的文本值
dom.Find(".td-02>a").Each(func (i int, selection *goquery.Selection) {
fmt.Println(selection.Text())
})
Attr() 返回节点的属性值以及该属性是否存在的布尔值
dom.Find("#execution").Each(func (i int, selection *goquery.Selection) {
value[i], ok = selection.Attr("value")
})
Length() 返回该Selection的元素个数
dom.Find("td").Length()
闲言
这个库用起来非常容易上手,尤其是对jQuery熟悉的同学,极大地提升了开发效率。
之前都是用Python写爬虫,使用BeautifulSoup进行解析,十分方便。第一次用go的net/html尝试解析的时候,花了很多不必要的时间,直到后来发现了goquery,才找回了用BeautifulSoup的感觉。
友情提示:爬虫有风险,请务必遵守法律法规
参考资料
https://github.com/PuerkitoBio/goquery
https://www.flysnow.org/2018/01/20/golang-goquery-examples-selector.html
本文来自:51CTO博客
感谢作者:mob604756f0bbf4
查看原文:【GoCN酷Go推荐】Html解析利器-goquery库
相关阅读 >>
Golang 协程(Goroutine) 运行过程 与 并发
更多相关阅读请进入《Go》频道 >>

Go语言101
一个与时俱进的Go编程知识库。