【问题标题】:Requests library crashing on Python 2 and Python 3 with请求库在 Python 2 和 Python 3 上崩溃
【发布时间】:2013-06-13 10:55:51
【问题描述】:

我正在尝试使用以下代码解析带有 requestsBeautifulSoup 库的任意网页:

try:
    response = requests.get(url)
except Exception as error:
    return False

if response.encoding == None:
    soup = bs4.BeautifulSoup(response.text) # This is line 809
else:
    soup = bs4.BeautifulSoup(response.text, from_encoding=response.encoding)

在大多数网页上都可以正常工作。但是,在某些任意页面 (

Traceback (most recent call last):
  File "/home/dotancohen/code/parser.py", line 155, in has_css
    soup = bs4.BeautifulSoup(response.text)
  File "/usr/lib/python3/dist-packages/requests/models.py", line 809, in text
    content = str(self.content, encoding, errors='replace')
  TypeError: str() argument 2 must be str, not None

供参考,这是requests库的相关方法:

@property
def text(self):
    """Content of the response, in unicode.

    if Response.encoding is None and chardet module is available, encoding
    will be guessed.
    """

    # Try charset from content-type
    content = None
    encoding = self.encoding

    # Fallback to auto-detected encoding.
    if self.encoding is None:
        if chardet is not None:
            encoding = chardet.detect(self.content)['encoding']

    # Decode unicode from given encoding.
    try:
        content = str(self.content, encoding, errors='replace') # This is line 809
    except LookupError:
        # A LookupError is raised if the encoding was not found which could
        # indicate a misspelling or similar mistake.
        #
        # So we try blindly encoding.
        content = str(self.content, errors='replace')

    return content

可以看出,当抛出此错误时,我没有传入编码。 我如何不正确地使用该库,我可以做些什么来防止这个错误?这是在 Python 3.2.3 上,但我也可以在 Python 2 上得到相同的结果。

【问题讨论】:

    标签: python exception beautifulsoup python-requests


    【解决方案1】:

    这意味着服务器没有发送标题中内容的编码,chardet 库也无法确定内容的编码。实际上,您故意测试是否缺少编码;如果没有可用的编码,为什么要尝试获取解码的文本?

    您可以尝试将解码留给BeautifulSoup 解析器:

    if response.encoding is None:
       soup = bs4.BeautifulSoup(response.content)
    

    并且没有需要将编码传递给BeautifulSoup,因为如果.text没有失败,那么您使用的是Unicode,并且BeautifulSoup无论如何都会忽略编码参数:

    else:
       soup = bs4.BeautifulSoup(response.text)
    

    【讨论】:

    • 谢谢马丁!使用这段代码,我已经解析了大约 1000 个 URL,没有任何问题,所以看起来这实际上是解决方案!
    • .text 失败,因为服务器没有可用的编码,或者您没有chardet(它带有 requests,捆绑)或@ 987654329@ 无法确定编码。后者必须做出有根据的猜测,有时会失败。
    • 我明白了。非常感谢,非常感谢您的见解!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多