2023年6月29日发(作者:)
golang解析⽹页的第三⽅包——goquery(爬⾍必备)goquery是⼀个使⽤go语⾔写成的HTML解析库,可以让你像jQuery那样的⽅式来操作DOM⽂档,使⽤起来⾮常的简便。
⼀、官⽹下载地址⼆、goquery提供的主要结构体和⽅法
2.1. Document 代表⼀个HTML⽂档, 1 Document 继承了Selection 类型,因此,Document 可以直接使⽤ Selection 类型的⽅法。 2 Document初始化的五种⽅式 1)根据根节点初始化 func return newDocument(root, nil)
2)根据url初始化,⽐较常⽤ func return nil, e return NewDocumentFromResponse(res)
3)根据io的Reader初始化 func return nil, e return newDocument(root, nil), nil
4) 根据http的Response初始化,也⽐较常⽤unc NewDocume return nil, ("Response is nil") return nil, ("t is nil") return nil, e return newDocument(root, ), nil
5) 复制⼀个⽂档对象 return newDocument(cloneNode(de), )
ion Selection匹配⼀些条件后的节点集合(Nodes)
2.3 Selection类型提供的⽅法,这些⽅法是页⾯解析最重要,最核⼼的⽅法1)类似函数的位置操作
- Eq(index int) *Selection //根据索引获取某个节点集 - First() *Selection //获取第⼀个⼦节点集 - Last() *Selection //获取最后⼀个⼦节点集 - Next() *Selection //获取下⼀个兄弟节点集 - NextAll() *Selection //获取后⾯所有兄弟节点集 - Prev() *Selection //前⼀个兄弟节点集 - Get(index int) * //根据索引获取⼀个节点 - Index() int //返回选择对象中第⼀个元素的位置 - Slice(start, end int) *Selection //根据起始位置获取⼦节点集
2)扩⼤ Selection 集合(增加选择的节点) - Add(selector string) *Selection //将匹配到的节点添加当前节点集合中 - AndSelf() *Selection //将堆栈上的前⼀组元素添加到当前的 - Union() *Selection //which is an alias for AddSelection()
3)过滤⽅法,减少节点集合 - End() *Selection - Filter…() //过滤 - Has…() - Intersection() //which is an alias of FilterSelection() - Not…()
4)循环遍历选择的节点 - Each(f func(int, *Selection)) *Selection //遍历 - EachWithBreak(f func(int, *Selection) bool) *Selection //可中断遍历 - Map(f func(int, *Selection) string) (result []string) //返回字符串数组
5)修改⽂档 - After…() //在匹配元素之后追加元素 - Append…() //将选择器指定的元素添加到匹配元素集合的每个元素的末尾 - Before…() //在匹配元素之前追加元素 - Clone() //创建匹配节点的副本 - Empty() //清空⼦节点 - Prepend…() - Remove…() - ReplaceWith…() - Unwrap() - Wrap…() - WrapAll…() - WrapInner…()
6)检测或获取节点属性值 - Attr(), RemoveAttr(), SetAttr() //获取,移除,设置属性的值 - AddClass(), HasClass(), RemoveClass(), ToggleClass()
- Html() //获取该节点的html - Length() //返回该Selection的元素个数 - Size(), which is an alias for Length() - Text() //获取该节点的⽂本值
7)查询或显⽰⼀个节点的⾝份 - Contains() //包含 - Is…()
8)在⽂档树之间来回跳转(常⽤的查找节点⽅法) - Children…() - Contents() - Find…() - Next…() - Parent[s]…() - Prev…() - Siblings…()
三、例⼦
发布者:admin,转转请注明出处:http://www.yc00.com/web/1687985143a63862.html
评论列表(0条)