python - 检查 "response.content"中的字符串引发 "TypeError: a bytes-like object is required, not ' str'"

标签 python python-3.x string 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')

我收到以下错误:

TypeError: a bytes-like object is required, not 'str'

我不太确定为什么会发生这种情况以及解决方案是什么。

最佳答案

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

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

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

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

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

关于python - 检查 "response.content"中的字符串引发 "TypeError: a bytes-like object is required, not ' str'",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48997007/

相关文章:

python数据抓取改变货币

Python asyncio子进程连续写入stdin和读取stdout/stderr

python - 如何抑制 web.py 输出?

c# - 如何释放或回收 C# 中的字符串?

python - 获取 URL 列表的内容

python - 如何使用 selenium python webdriver 计算来自 Web 应用程序的表中的行数

java - 检查输入的字符串长度是否等于三

java - 不区分大小写的 String.contains 方法的替代方法是什么?

python - 无法在 Mac 上为 python 3 安装 MySQL 连接器/python

python - 异步和 rabbitmq (asynqp) : how to consume from multiple queues concurrently