Golang 自动识别网页编码并读取内容

在 Golang 中,可以使用第三方库 'golang.org/x/net/html/charset' 来获取文本的编码并解码网页内容。以下是一段代码示例:goimport ( 'golang.org/x/net/html/charset' 'golang.org/x/text/encoding' 'golang.org/x/text/transform' 'io/ioutil' 'net/http')

func getCharset(resp *http.Response) encoding.Encoding { contentType := resp.Header.Get('Content-Type') _, params, err := charset.ParseMediaType(contentType) if err != nil { return nil } charset, err := charset.Lookup(params['charset']) if err != nil { return nil } return charset}

func getBody(resp *http.Response) ([]byte, error) { defer resp.Body.Close() charset := getCharset(resp) if charset == nil { return ioutil.ReadAll(resp.Body) } reader := transform.NewReader(resp.Body, charset.NewDecoder()) return ioutil.ReadAll(reader)}

代码解析:

  1. getCharset 函数: - 首先,从 HTTP 响应头部的 'Content-Type' 字段中获取编码信息。 - 然后,使用 charset.ParseMediaType 函数解析 'Content-Type' 字符串,提取编码参数。 - 最后,使用 charset.Lookup 函数查找对应的编码方式,并返回 encoding.Encoding 对象。2. getBody 函数: - 首先,调用 getCharset 函数获取网页编码。 - 如果成功获取编码,则使用 transform.NewReader 创建一个新的 Reader,该 Reader 使用获取到的编码方式解码 resp.Body 中的数据流。 - 最后,使用 ioutil.ReadAll 函数读取解码后的数据并返回。

使用方法:

  1. 使用 http.Get 函数发送 HTTP 请求。2. 调用 getBody 函数获取解码后的网页内容。

**示例:**goresp, err := http.Get('https://www.example.com')if err != nil { // 处理错误}body, err := getBody(resp)if err != nil { // 处理错误}fmt.Println(string(body)) // 打印网页内容

这段代码可以帮助你自动识别网页编码并读取网页内容,方便后续处理。

Golang 自动识别网页编码并读取内容

原文地址: https://www.cveoy.top/t/topic/fYLl 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录