请求模块编码提供不同的编码然后HTML编码

The*_*nse 2 python encoding python-requests

请求模块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
Run Code Online (Sandbox Code Playgroud)

输出:

ISO-8859-1
Run Code Online (Sandbox Code Playgroud)

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进行编码时,值已经变为ie)á更改为此Ã

有没有办法将所有类型的编码转换为UTF-8?

Jav*_*ero 5

请求将首先检查 HTTP 标头中的编码:

print obj.headers['content-type']
Run Code Online (Sandbox Code Playgroud)

输出:

text/html
Run Code Online (Sandbox Code Playgroud)

没有正确解析编码猜测的类型,因此它指定了默认的 ISO-8859-1。

文档中查看更多信息。


Mar*_*ers 5

请求将response.encoding属性设置为ISO-8859-1您有text/*响应并且响应标头中未指定任何内容类型.

请参阅高级文档编码部分:

唯一的一次请求不会做到这一点,如果没有明确的字符集是存在于HTTP头,并Content-Type头中包含text.在这种情况下,RFC 2616指定默认字符集必须是ISO-8859-1.在这种情况下,请求遵循规范.如果需要不同的编码,可以手动设置Response.encoding属性,或使用raw Response.content.

大胆强调我的.

您可以通过charsetContent-Type标头中查找参数来测试:

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

您的HTML文档指定<meta>标题中的内容类型,并且此标题是权威的:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
Run Code Online (Sandbox Code Playgroud)

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

如果HTML页面包含具有不同编解码器的标头,则不应将HTML页面重新编码为UTF-8.在这种情况下,您必须至少纠正该标题.

使用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
Run Code Online (Sandbox Code Playgroud)

同样,其他文件标准也可以规定具体的编码; 例如,XML总是UTF-8,除非由<?xml encoding="..." ... ?>XML声明指定,再次是文档的一部分.