【问题标题】:Python: UnicodeDecodeError: 'utf-8' codec can't decode byte...invalid continuation bytePython:UnicodeDecodeError:'utf-8'编解码器无法解码字节...无效的继续字节
【发布时间】:2014-12-24 02:28:37
【问题描述】:

我正在 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 上。即使有同样的错误,我直到昨天才出现这个错误。然后今天我再次运行程序,弹出错误..

关于如何诊断错误的任何线索?

【问题讨论】:

    标签: python unicode utf-8 beautifulsoup urllib


    【解决方案1】:

    您应该解码响应。首先,您错误地假设响应是 UTF-8 编码的(事实并非如此,如错误所示),但更重要的是,BeautifulSoup 会为您检测编码。请参阅 BeautifulSoup 文档的 Encodings section

    将一个字节字符串传递给 BeautifulSoup,它会使用任何 &lt;meta&gt; 标头来声明正确的编码,或者为您自动检测编码做得很好。

    如果自动检测失败,您可以随时回退到服务器提供的编码:

    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,但如果服务器在 Content-Type 标头中包含 charset 参数,则以上假设服务器已正确配置并强制 BeautifulSoup 使用该编码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-22
      • 2021-03-12
      • 1970-01-01
      • 2018-01-11
      • 2020-11-02
      • 2021-01-02
      • 2021-04-27
      相关资源
      最近更新 更多