http - 如何在 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)返回错误的页面。不知道有没有关系。
我将为第二个问题打开一个新线程。
解决方案
NewReader的第二个参数被记录为字符编码,contentType
而不是字符编码。这意味着它需要Content-Type
HTTP 标头中的字段值。因此,正确的用法是:
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 中错误声明的字符集编码。
推荐阅读
- git - 从第二个存储库文件在一个存储库中创建分支
- lisp - Hashtable 不保留 Lisp 中的插入顺序
- python - 如何使用 Python 在 Photoshop 中编辑/打开智能对象?
- java - Java 对象字段值取决于其他字段 - 最佳实践模式?
- c++ - 我怎么知道我的代码是否已经编译?
- r - 如何使用 R 获取数据框中每个列对的相关系数?
- javascript - 文本区域中的值不会在 REACT 中被删除
- owl - OWL 与 Schema.org 有何不同?
- machine-learning - 校准神经网络的概率
- azure-devops - 如何将现有区域添加到现有团队?