1、描述
golang默认编码为utf-8,goquery也一样,默认处理的utf-8的页面。但网页中会有各种格式像常见的"gb2312","gbk"等。处理这些编码的网页时就会出现头大的乱码.golang没有自带的编解码包,需要借助第三方包处理。
2、simplifiedchinese 处理GBK编码##
第三方的编码包很多,我这里使用的是simplifiedchinese。因为simplifiedchinese和其它的相比,它不需要gcc的支持。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19package util import ( "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的时候,把编码异常的字符转过来就是。
如:
复制代码
1
2
3
4
5
6
7
8
9
10
11doc, _ := 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()方法
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21// 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()方法:
复制代码
1
2
3
4
5
6
7
8func (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 }
优雅地使用:
复制代码
1
2
3
4
5
6doc, _ := goquery.NewDocument(url) name, _ := doc.Find("div.name").First().GBKHtml() age, _ := doc.Find("div.age").First().GBKHtml()
最后
以上就是懵懂白开水最近收集整理的关于goquery 增加GBK支持的全部内容,更多相关goquery内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复