我正在 Python 3.3 上使用 BeautifulSoup 构建一个网络抓取工具
但是我遇到了一个问题,它阻止我获得可以与 BeautifulSoup 一起使用的有效字符串*。即:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe0 in position 7047: invalid continuation byte
我知道有很多类似的问题,但到目前为止我还没有找到一种方法可以帮助我诊断以下代码的问题:
import urllib.request
URL = "<url>" # sorry, I cannot show the url for privacy reasons, but it's a normal html document
page = urllib.request.urlopen(URL)
page = page.read().decode("utf-8") # from bytes to <source encodings>
正如我所猜测的,我注意到此错误仅发生在某些 URL 上,而不会发生在其他 URL 上。即使出现同样的错误,直到昨天我才出现此错误。然后今天我再次运行程序,又弹出错误..
有关如何诊断错误的任何线索吗?
最佳答案
您不应该对响应进行解码。首先,您错误地假设响应是 UTF-8 编码的(事实并非如此,如错误所示),但更重要的是,BeautifulSoup 将为您检测编码。请参阅Encodings section BeautifulSoup 文档。
将字节字符串传递给 BeautifulSoup,它将使用任何 <meta>
header 声明正确的编码,或者为您自动检测编码。
如果自动检测失败,您始终可以回退到服务器提供的编码:
encoding = page.info().get_charset()
page = page.read()
soup = BeautifulSoup(page)
if encoding is not None and soup.original_encoding != encoding:
print('Server and BeautifulSoup disagree')
print('Content-type states it is {}, BS4 states thinks it is {}'.format(encoding, soup.original_encoding)
print('Forcing encoding to server-supplied codec')
soup = BeautifulSoup(page, from_encoding=encoding)
这仍然将实际解码留给 BeautifulSoup,但如果服务器包含 charset
Content-Type
中的参数header 那么上面的内容假设服务器配置正确并强制 BeautifulSoup 使用该编码。
关于Python:UnicodeDecodeError: 'utf-8'编解码器无法解码字节...无效的连续字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26612492/