检查"response.content"中的字符串,引发"TypeError:需要类似字节的对象,而不是'str'"

Pie*_*mas 6 python string bytestring python-3.x python-requests

我试图查看一个句子是否存在于请求的响应中.

import requests

r = requests.get('https://www.eventbrite.co.uk/o/piers-test-16613670281')
text = 'Sorry, there are no upcoming events'

if text in r.content: 
   print('No Upcoming Events')
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

TypeError: a bytes-like object is required, not 'str'
Run Code Online (Sandbox Code Playgroud)

我不太清楚为什么会发生这种情况以及解决方案会是什么.

Moi*_*dri 8

r.contentbytes在Python 3.x中返回一个类似的对象.要检查,请执行:

>>> type(r.content)
<class 'bytes'>
Run Code Online (Sandbox Code Playgroud)

有多种方法可以解决您的问题.例如:

  1. 解码r.content为字符串:您可以将decode其作为字符串:

    >>> text in r.content.decode()
    False
    
    Run Code Online (Sandbox Code Playgroud)
  2. 转换r.contentutf-8字符串为:

    >>> text in str(r.content, 'utf-8')
    False
    
    Run Code Online (Sandbox Code Playgroud)
  3. 将您text的搜索定义为字节字符串.例如:

    text = b'Sorry, there are no upcoming events'
    #      ^  note the `b` here
    
    Run Code Online (Sandbox Code Playgroud)

    现在你可以简单地用它r.content作为:

    >>> text in r.content
    False
    
    Run Code Online (Sandbox Code Playgroud)
  4. 使用r.text而不是r.content搜索字符串,如文档所示:

    访问时使用由请求猜测的文本编码r.text.

    因此你可能会这样做:

    >>> text in r.text
    False
    
    Run Code Online (Sandbox Code Playgroud)


hee*_*ayl 6

r.content是一个bytes对象,但textstr,所以你不能做__contains__(in另一个直接)检查.

您可以轻松地(重新)将text对象定义为bytestring:

text = b'Sorry, there are no upcoming events'
Run Code Online (Sandbox Code Playgroud)

现在,你可以做到if text in r.content:.

或者您可以使用直接r.text获取str表示,并按text原样使用(as str).