检查字符串“响应.内容“引发”TypeError:需要类似字节的对象,而不是“str”

2024-10-01 15:31:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我想看看请求回复中是否有句子。在

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')

我得到以下错误:

^{pr2}$

我不太清楚为什么会发生这种情况,以及解决办法是什么。在


Tags: texthttpstestimportgetwwwrequestsare
3条回答

试试这个:

if text in r.text:

^{}是返回的文本内容。^{}是返回的二进制内容。在

^{}在Python 3.x中返回一个类似于bytes的对象。要进行检查,请执行以下操作:

>>> type(r.content)
<class 'bytes'>

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

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

    ^{2美元
  2. r.content转换为utf-8字符串为:

    >>> text in str(r.content, 'utf-8')
    False
    
  3. 定义您的text以字节字符串的形式搜索。例如:

    text = b'Sorry, there are no upcoming events'
    #      ^  note the `b` here
    

    现在您只需将其与r.content一起使用,如下所示:

    >>> text in r.content
    False
    
  4. 使用^{}而不是r.content来搜索字符串,正如document建议的那样:

    The text encoding guessed by Requests is used when you access r.text.

    因此,您只需:

    >>> text in r.text
    False
    

r.content是一个bytes对象,但是text是{},所以不能直接对另一个对象执行__contains__in)检查。在

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

text = b'Sorry, there are no upcoming events'

现在,您可以执行if text in r.content:。在

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

相关问题 更多 >

    热门问题