如何避免 scrapy 中的错误“TypeError: a bytes-like object is required, not 'str'”

neg*_*aro 5 python string scrapy python-3.x

    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)
Run Code Online (Sandbox Code Playgroud)

我参考文档尝试了上面的代码,但是出现了以下错误。

    if "authentication failed" in response.body:
TypeError: a bytes-like object is required, not 'str'
Run Code Online (Sandbox Code Playgroud)

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

我很好奇,一般来说,如果登录失败,response.body中是否会显示“身份验证失败”?

感谢您阅读我的问题。

Nan*_*esh 6

您也可以使用response.text,因为它也会返回正文,但作为string. 因此,您不必string you are searching显式地将对象转换为字节对象。

if 'authentication failed' in response.text:
   #Do something
Run Code Online (Sandbox Code Playgroud)


Mar*_*ers 2

response.body是一个bytes值,但是"authentication failed"是一个str. 你不能混合使用这些类型。

使用bytes文字:

if b"authentication failed" in response.body:
Run Code Online (Sandbox Code Playgroud)