goquery 增加GBK支持

来源:互联网 发布:淘宝描述图片尺寸最大 编辑:程序博客网 时间:2024/04/29 23:16

1、描述

golang默认编码为utf-8,goquery也一样,默认处理的utf-8的页面。但网页中会有各种格式像常见的”gb2312”,”gbk”等。处理这些编码的网页时就会出现头大的乱码.golang没有自带的编解码包,需要借助第三方包处理。

2、simplifiedchinese 处理GBK编码

第三方的编码包很多,我这里使用的是simplifiedchinese。因为simplifiedchinese和其它的相比,它不需要gcc的支持。

package utilimport (    "golang.org/x/text/encoding/simplifiedchinese")func DecodeToGBK(text string) (string, error) {    dst := make([]byte, len(text)*2)    tr := simplifiedchinese.GB18030.NewDecoder()    nDst, _, err := tr.Transform(dst, []byte(text), true)    if err != nil {        return text, err    }    return string(dst[:nDst]), nil}

3、goquery简单转换GBK

下面我们在使用goquery的时候,把编码异常的字符转过来就是。
如:

doc, _ := goquery.NewDocument(url)nameNode := doc.Find("div.name").First()name, _ := nameNode.Html()name, _ = util.DecodeToGBK(name)ageNode := doc.Find("div.age").First()age, _ := ageNode.Html()age, _ = util.DecodeToGBK(age)

4、重写goquery 中的方法支持GBK

像上面的编码转换的过程一样,如果多个节点需要编码转换,那么我们的业务代码显得很臃肿,不够优雅。我们可以在goquery Selection对象原有的方法上,增加一些对GBK支持的方法。

原有Html()方法

// Html gets the HTML contents of the first element in the set of matched// elements. It includes text and comment nodes.func (s *Selection) Html() (ret string, e error) {    // Since there is no .innerHtml, the HTML content must be re-created from    // the nodes using html.Render.    var buf bytes.Buffer    if len(s.Nodes) > 0 {        for c := s.Nodes[0].FirstChild; c != nil; c = c.NextSibling {            e = html.Render(&buf, c)            if e != nil {                return            }        }        ret = buf.String()    }    return}

增加GBK支持的GBKHtml()方法:

func (s *Selection) GBKHtml() (ret string, e error) {    // Since there is no .innerHtml, the HTML content must be re-created from    // the nodes using html.Render.    ret, _ = s.Html()    ret, _ = util.DecodeToGBK(ret)    return}

优雅地使用:

doc, _ := goquery.NewDocument(url)name, _ := doc.Find("div.name").First().GBKHtml()age, _ := doc.Find("div.age").First().GBKHtml()
0 0
原创粉丝点击