Loading... Goquery是一个Html解析库。其部分操作很接近 `JQuery`的选择器。基本上会用jquery的,Goquery基本可以1分钟上手。 # 安装 ```shell go get github.com/PuerkitoBio/goquery ``` 然后引入 ```Golang import "github.com/PuerkitoBio/goquery" ``` <!--more--> # 创建文档 ```Golang dom,err := goquery.NewDocumentFromReader(strings.NewReader(html)) dom.Find("p").Each(func(i int, selection *goquery.Selection) { fmt.Println(selection.Text()) }) ``` # 选择器 上面的例子中,我们使用了**元素选择器**,就是 `Find("p")`的部分,我们选择了整个网页里面的 `p`标签,goquery跟jquery一样都支持很多选择器。常用的有: 1. ID选择器 `div#title` 选择id为title的div标签 2. CSS选择器 `div.title` 选择class为title的div标签 3. 属性选择器 `a[href=123]` 选择href为123的a标签 除此之外,还有很多选择器和过滤器的语法,可以看[爬虫全家桶—Goquery选择器][1]。 # 选择器或(|)运算 `Find("selector1, selector2, selectorN")`表示只要满足其中一个选择器就可以被筛选出来,也就是选择器的或(|)运算操作。 # 操作 ## 类似函数的位置操作 * `Find(selection) *Selection` //根据选择器查找节点集 * `Eq(index int) *Selection` //根据索引获取某个节点集 * `First() *Selection` //获取第一个子节点集 * `Last() *Selection` //获取最后一个子节点集 * `Next() *Selection` //获取下一个兄弟节点集 * `NextAll() *Selection` //获取后面所有兄弟节点集 * `Prev() *Selection` //前一个兄弟节点集 * `Get(index int) *html.Node` //根据索引获取一个节点 * `Index() int` //返回选择对象中第一个元素的位置 * `Slice(start, end int) *Selection` //根据起始位置获取子节点集 ## 循环遍历选择的节点 * `Each(f func(int, *Selection)) *Selection` //遍历 * `EachWithBreak(f func(int, *Selection) bool) *Selection` //可中断遍历 * `Map(f func(int, *Selection) string) (result []string)` //返回字符串数组 ## 检测或获取节点属性值 * `Attr(), RemoveAttr(), SetAttr()` //获取,移除,设置属性的值 * `AddClass(), HasClass(), RemoveClass(), ToggleClass()` //添加,验证存在,删除,切换class的值 * `Html()` //获取该节点的html * `Length()` //返回该Selection的元素个数 * `Text()` //获取该节点的文本值 ## 在文档树之间来回跳转(常用的查找节点方法) * `Children()` //返回selection中各个节点下的孩子节点 * `Contents()` //获取当前节点下的所有节点 * `Find()` //查找获取当前匹配的元素 * `Next()` //下一个元素 * `Prev()` //上一个元素 [1]: https://athorx.com/archives/24/ Last modification:November 8th, 2020 at 01:27 pm © 允许规范转载