首页 > 解决方案 > 如何在 Go 中请求具有特定字符集的页面?

问题描述

我正在将一个软件从 Python 重写为 Go。我http.Get在获取以iso-8859-1. Python 版本正在运行,但 Go 中的版本不可用。

这是有效的:Python

r = requests.get("https://www.bger.ch/ext/eurospider/live/de/php/aza/http/index.php?lang=de&type=show_document&print=yes&highlight_docid=aza://27-01-2016-5A_718-2015")
r.encoding = 'iso-8859-1'
file = open('tmp_python.txt', 'w')
file.write(r.text.strip())
file.close()

这不起作用:去

package main

import (
    "golang.org/x/net/html/charset"
    "io/ioutil"
    "log"
    "net/http"
)

func main() {
    link := "https://www.bger.ch/ext/eurospider/live/de/php/aza/http/index.php?lang=de&type=show_document&print=yes&highlight_docid=aza://27-01-2016-5A_718-2015"
    resp, err := http.Get(link)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    reader, err := charset.NewReader(resp.Body, "iso-8859-1")
    if err != nil {
        panic(err)
    }

    content, err := ioutil.ReadAll(reader)
    if err != nil {
        panic(err)
    }
    log.Println(string(content))
}

我的浏览器和 Python 给出了相同的结果,但 Go 版本没有。我该如何解决?

编辑

我认为 Go 有重定向。Python不会发生这种情况。

编辑 2

我的问题写得不好。我有两个问题:1)编码 2)返回错误的页面。不知道有没有关系。

我将为第二个问题打开一个新线程。

标签: httpgo

解决方案


NewReader的第二个参数被记录为字符编码,contentType而不是字符编码。这意味着它需要Content-TypeHTTP 标头中的字段值。因此,正确的用法是:

reader, err := charset.NewReader(resp.Body, "text/html; charset=iso-8859-1")

这非常有效。

请注意,如果给定的contentType内部没有有用的字符集定义,它将查看正文本身以确定字符集。而这个页面的HTTP头有一个明确的

Content-Type: text/html;charset=iso-8859-1

返回的实际 HTML 文档定义了不同的字符集编码:

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

如果代码中的设置错误contentType,它将因此采用 HTML 中错误声明的字符集编码。


推荐阅读