python - 请求模块编码提供了与 HTML 编码不同的编码

标签 python python-requests content-encoding

请求模块encoding提供的编码与HTML页面中实际设置的编码不同

代码:

import requests
URL = "http://www.reynamining.com/nuevositio/contacto.html"
obj = requests.get(URL, timeout=60, verify=False, allow_redirects=True)
print obj.encoding

输出:

ISO-8859-1

HTML 中设置的实际编码是 UTF-8 content="text/html; charset=UTF-8"

我的问题是:

  1. 为什么 requests.encoding 显示的编码与 HTML 页面中描述的编码不同?

我正在尝试使用此方法将编码转换为 UTF-8 objReq.content.decode(encodes).encode("utf-8") 因为它已经在 UTF 中-8 当我使用 ISO-8859-1 解码并使用 UTF-8 编码时,值会发生变化,即)á更改为此 Ã

有什么方法可以将所有类型的编码转换为 UTF-8 吗?

最佳答案

请求设置 response.encoding属性为 ISO-8859-1当你有 text/*响应,但在响应 header 中未指定内容类型。

参见 Encoding section of the Advanced documentation :

The only time Requests will not do this is if no explicit charset is present in the HTTP headers and the Content-Type header contains text. In this situation, RFC 2616 specifies that the default charset must be ISO-8859-1. Requests follows the specification in this case. If you require a different encoding, you can manually set the Response.encoding property, or use the raw Response.content.

大胆强调我的。

您可以通过查找 charset 来对此进行测试Content-Type 中的参数 header :

resp = requests.get(....)
encoding = resp.encoding if 'charset' in resp.headers.get('content-type', '').lower() else None

您的 HTML 文档在 <meta> 中指定了内容类型header,而这个header才是权威的:

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

HTML 5 还定义了一个 <meta charset="..." />标签,参见 <meta charset="utf-8"> vs <meta http-equiv="Content-Type">

如果 HTML 页面包含具有不同编解码器的此类 header ,则您不应将 HTML 页面重新编码为 UTF-8。在这种情况下,您至少必须更正该 header

使用 BeautifulSoup:

# pass in explicit encoding if set as a header
encoding = resp.encoding if 'charset' in resp.headers.get('content-type', '').lower() else None
content = resp.content
soup = BeautifulSoup(content, from_encoding=encoding)
if soup.original_encoding != 'utf-8':
    meta = soup.select_one('meta[charset], meta[http-equiv="Content-Type"]')
    if meta:
        # replace the meta charset info before re-encoding
        if 'charset' in meta.attrs:
            meta['charset'] = 'utf-8'
        else:
            meta['content'] = 'text/html; charset=utf-8'
    # re-encode to UTF-8
    content = soup.prettify()  # encodes to UTF-8 by default

类似地,其他文档标准也可能指定特定的编码;例如,XML 始终是 UTF-8,除非由 <?xml encoding="..." ... ?> 指定。 XML 声明,也是文档的一部分。

关于python - 请求模块编码提供了与 HTML 编码不同的编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36453359/

相关文章:

python - 如何使用 API 和 Python 提取数据?

python - 使用 requests 在 Python 中下载 SSRS 报告

python - 通过 multipart/form-data POST 请求发送内存中的字节(文件)。 Python

asp.net-core - 替代 HttpResponse.ContentEncoding ASP.NET 5

python - 在 Python 中显示 HTML 请求时编码错误

python - “heroku run python manage.py migrate”失败并出现错误 'Error R13 (Attach error) -> Failed to attach to process'

python - 在python中的字符串中查找unicodes的所有匹配项

python - Django Channels 停止使用 self.receive_lock.locked 错误

python - 可以在 Google App Engine 上使用 Python Requests 库吗?

PHP ob_gzhandler,设置 Content-Length 禁用 gzip 压缩输出