我正在将软件从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)返回错误的页面。不知道有没有关系。
我将为第二个问题打开一个新线程。
最佳答案
NewReader的第二个参数记录为contentType
而不是字符编码。这意味着它期望使用HTTP header 中的Content-Type
字段的值。因此,正确的用法是:
reader, err := charset.NewReader(resp.Body, "text/html; charset=iso-8859-1")
这完美地工作。
请注意,如果给定的
contentType
内部没有有用的字符集定义,它将查看主体本身以确定字符集。并且尽管此页的HTTP header 有一个清晰的Content-Type: text/html;charset=iso-8859-1
返回的实际HTML文档定义了不同的字符集编码:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
如果您的代码中
contentType
设置错误,它将采用HTML中错误声明的字符集编码。
关于http - 如何在Go中请求具有特定字符集的页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60106092/