python - utf-8中字符的编码问题

标签 python utf-8 beautifulsoup python-requests mojibake

我通过 a.get('href') 使用漂亮的汤库从网页获取链接。在链接中有一个奇怪的字符 ® 但当我得到它时它变成了 ®。我怎样才能正确编码?我已经在页面开头添加了# -*- coding: utf-8 -*-

r = requests.get(url)

soup = BeautifulSoup(r.text)

最佳答案

不要使用r.text ;将解码留给 BeautifulSoup :

soup = BeautifulSoup(r.content)

r.content 以字节为单位为您提供响应,无需解码。 r.text 另一方面,响应是否解码为 unicode .

发生的事情是服务器没有在响应 header 中包含字符集。在那一刻,requests遵循 HTTP RFC 2261, section 3.7.1 : text/响应默认应使用 ISO-8859-1(拉丁语 1)字符集。

对于您的 HTML 页面,该默认值是错误的,并且您得到了错误的结果; r.text将字节解码为 Latin-1,导致 Mojibake :

>>> print u'®'.encode('utf8').decode('latin1')
®

HTML 本身可以在 HTML 页面本身中包含正确的编码,格式为 <meta> tag在 HTML header 中。 BeautifulSoup 将使用该 header 并为您解码字节。

即使 <meta>缺少 header 标签,BeautifulSoup 包括其他方法 auto-detect encodings .

关于python - utf-8中字符的编码问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24790258/

相关文章:

python - 使用 asyncore 读取网站

python - 如何获取当前的 python 日志记录配置?

Python:导入问题

c++ - std::codecvt_utf8_utf16 不会在大端中将 utf-8 转换为 utf-16

utf-8 - Mechanize 将 - char 转换为 -

python - 如何使用 Beautifulsoup Python 检索拍卖时间

python - 使用 python beautifulsoup 抓取 NBA 高级统计数据

python - ipython qt 控制台 : change the default working directory

MySQL - 使用 LOAD DATA LOCAL INFILE 加载西里尔文数据

Python:充满 BOM 的 Youtube HTML