goquery

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对象。

    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和相应资源后能在本地查看)

    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)
            }
        }
    })

踩坑

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

document.Find("head")

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

`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/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值