码迷,mamicode.com
首页 > 其他好文 > 详细

golang 编码转换 gbk转码utf 爬虫中文乱码

时间:2019-06-08 14:49:51      阅读:286      评论:0      收藏:0      [点我收藏+]

标签:decode   com   定义   data   rcc   tostring   转码   编码转换   coder   

 

golang仅支持utf-8, 使用爬虫时经常遇到不是utf-8编码的文件, 如果抓取则会造成文字乱码

 

1. 下载导入包

import "github.com/axgle/mahonia"

2. 定义函数

func ConvertToString(src string, srcCode string, tagCode string) string {

    srcCoder := mahonia.NewDecoder(srcCode)

    srcResult := srcCoder.ConvertString(src)

    tagCoder := mahonia.NewDecoder(tagCode)

    _, cdata, _ := tagCoder.Translate([]byte(srcResult), true)

    result := string(cdata)

    return result

}

3. 调用函数

result = ConvertToString(html, "gbk", "utf-8")

golang 编码转换 gbk转码utf 爬虫中文乱码

标签:decode   com   定义   data   rcc   tostring   转码   编码转换   coder   

原文地址:https://www.cnblogs.com/xsly/p/10990575.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!