我是靠谱客的博主 忧心硬币,这篇文章主要介绍goquerygoquery,现在分享给大家,希望可以做个参考。

goquery

介绍:goquery是一个使用go语言写成的HTML解析库,可以让你像jQuery那样的方式来操作DOM文档。

获取源码

goquery在github上开源。地址:
https://github.com/PuerkitoBio/goquery.
获取代码:
go get https://github.com/PuerkitoBio/goquery
在代码中引用时:
import “github.com/PuerkitoBio/goquery”

示例

获取解析html对象的document对象。

复制代码
1
2
document, err := goquery.NewDocumentFromReader(bytes.NewReader(body))

查找对应的元素

在查找元素的时候要注意对于div以及id所使用的前缀有所不同。
1. 这种形式的 不用变动
2. div class=”classname” document.Find(“.classname”)
3. div id=”idname” document.Find(“#idname”)
在查找到对应元素的时候可以采用Each函数对其中包含的各个selection进行迭代。
以下代码的目的是找到图片,并且把图片替换为本地路径.(实现下载html和相应资源后能在本地查看)

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
document.Find("body img").Each(func(idx int, s *goquery.Selection) { //把有深度的路径该问当前路径 src, exists := s.Attr("src") if exists && src != "" { fileName := getFileName(src) //分为绝对路径和相对路径 isContHttp := strings.Contains(src, "http") if isContHttp { //特殊处理 if strings.Contains(src, "aspx") { s.Remove() } else { err := downloadOneFile(ctx, src, downLoadpath, fileName, cookie) if err != nil { logger.Errorf("downloadOneFile err!! src:%s", src) downLoadErr = fmt.Sprintf("downloadOneFile err!! src:%s", src) } } } err := replaceNode(s, "src", "./"+fileName) if err != nil { logger.Errorf("convHtml replaceNode fail src", src, "filename", fileName) downLoadErr = fmt.Sprintf("convHtml replaceNode fail src:%s filename:%s n", src, fileName) } } })

踩坑

在项目实现的时候为了要获取头部内容。
使用以下代码时

复制代码
1
document.Find("head")

解析的总是里面header的内容,但是body不会。然而所需要的连接,css资源是在对应的header中,无法解析。场面一度非常尴尬。。
后来把这部分代码抠掉了之后使用正常。
大致思路是用获取后一个位置,使用切片去除。

复制代码
1
2
3
4
`match := "<!doctype html>"/**<!doctype html>*/ matchlastIndex := strings.LastIndex(string(body), match) matchLen := len([]byte(match)) body = body[(matchlastIndex + matchLen):]

踩坑二就是上面的使用find方法的时候没有区分id和class之间的区别。

参看资料

https://github.com/PuerkitoBio/goquery
http://blog.studygolang.com/2015/04/go-jquery-goquery/

最后

以上就是忧心硬币最近收集整理的关于goquerygoquery的全部内容,更多相关goquerygoquery内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(75)

评论列表共有 0 条评论

立即
投稿
返回
顶部