Golang 自动识别网页编码并读取内容
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)}
代码解析:
getCharset函数: - 首先,从 HTTP 响应头部的 'Content-Type' 字段中获取编码信息。 - 然后,使用charset.ParseMediaType函数解析 'Content-Type' 字符串,提取编码参数。 - 最后,使用charset.Lookup函数查找对应的编码方式,并返回encoding.Encoding对象。2.getBody函数: - 首先,调用getCharset函数获取网页编码。 - 如果成功获取编码,则使用transform.NewReader创建一个新的Reader,该 Reader 使用获取到的编码方式解码resp.Body中的数据流。 - 最后,使用ioutil.ReadAll函数读取解码后的数据并返回。
使用方法:
- 使用
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)) // 打印网页内容
这段代码可以帮助你自动识别网页编码并读取网页内容,方便后续处理。
原文地址: https://www.cveoy.top/t/topic/fYLl 著作权归作者所有。请勿转载和采集!