golang写爬虫出现乱码如何处理

golang写爬虫出现乱码如何处理?相信有很多人都不太了解,今天小编为了让大家更加了解Golang,所以给大家总结了以下内容,一起往下看吧。

golang写爬虫乱码怎么办

在用golang编写爬虫程序时,会碰见编码格式gb2312的页面。

网页页面上可以看出该页面字符编码为gb2312

<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />

而golang默认是支持UTF-8编码格式的,这样直接爬下来的结果会乱码。

解决方法:

使用 github.com/axgle/mahonia 这个包可以完成编码转换、

1、执行  go get github.com/axgle/mahonia 命令下载此包后,在%gopath%/src目录下会生产

github.com\axgle\mahonia

2、代码使用方法

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写爬虫出现乱码如何处理就分享到这里了,希望以上内容可以对大家有一定的参考价值,可以学以致用。如果喜欢本篇文章,不妨把它分享出去让更多的人看到。