python - 如何在 scrapy 中避免错误 "TypeError: a bytes-like object is required, not ' str'"

标签 python python-3.x string scrapy

    start_urls = ['https://github.com/login']

def parse(self, response):
    return scrapy.FormRequest.from_response(response,formdata={'login': 'xx',
                                            'password': 'xx'},callback=self.after_login)

def after_login(self, response):
    if "authentication failed" in response.body:
       self.logger.info("fail xx %s", response.body)

我引用文档试了上面的代码,但是出现如下错误。

    if "authentication failed" in response.body:
TypeError: a bytes-like object is required, not 'str'

它看起来像response.body 中的二进制文件。 有没有办法避免这个错误?

我很好奇,一般情况下,如果登录失败,response.body中是否会显示“authentication failed”?

感谢您阅读我的问题。

最佳答案

您还可以使用 response.text,因为它也会返回正文,但作为 string。因此,您不必将正在搜索的 string 显式转换为 bytes 对象。

if 'authentication failed' in response.text:
   #Do something

关于python - 如何在 scrapy 中避免错误 "TypeError: a bytes-like object is required, not ' str'",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45074438/

相关文章:

python - JSONDecodeError 在 Python3 中使用谷歌翻译 API

string - 排序重复字符串最快的方法是什么

python - 在 matplotlib 中编辑堆积条形图的 x 轴刻度标签

python - 在字符串列表上使用 strptime()。不能使用循环

python - 将字符串拆分为空白列表,当下一个字符不是破折号时不包括单个空格

python - 类内的 Numpy 数组赋值

java - 无法在 Nest Rest API 上设置温度

python - 无法使用请求从网页中抓取某个字段的值

c++ - 检查时感到困惑

java - 拆分和解析公式字符串