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
- goquery 增加GBK支持
- mysql支持gbk
- Ubuntu支持GBK编码
- 配置Cygwin支持GBK
- Eclipse GBK支持添加
- Eclipse GBK支持添加
- Ubuntu支持GBK
- Eclipse GBK支持添加
- Eclipse GBK支持添加
- Eclipse GBK支持添加
- Ubuntu支持GBK编码
- sublime Text2 GBK支持
- goquery使用
- 让linux支持gbk编码
- mac下eclipse支持GBK
- 让Ubuntu支持GBK编码
- ubuntu 中支持GBK编码
- CentOS 配置 mysql 支持 gbk
- c++使用类
- 按月份去旅游
- PHP获取某一天前后任意时间
- 排序算法-快速排序
- 将字符串中的所有空格去掉,要求时间复杂度O(N)
- goquery 增加GBK支持
- java中组合与继承的区别
- mha安装部署
- 欢迎使用CSDN-markdown编辑器
- Solr建立索引时,过滤HTML标签
- 文字溢出容器问题
- Oracle的时间总结 -- oracle知识2016/09/30
- 20160928_Oracle数据库管理记录
- uva 101