小编典典

如何在Go中请求具有特定字符集的页面?

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)返回错误的页面。不知道有没有关系。

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


阅读 247

收藏
2020-07-02

共1个答案

小编典典

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中错误声明的字符集编码。

2020-07-02