请求模块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"
我的问题是:
- 为什么
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 containstext
. In this situation, RFC 2616 specifies that the default charset must beISO-8859-1
. Requests follows the specification in this case. If you require a different encoding, you can manually set theResponse.encoding
property, or use the rawResponse.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/