首页 > 解决方案 > Python:有TypeError:需要一个类似字节的对象,而不是生成令牌时的'str'

问题描述

生成身份验证令牌时出现以下错误:

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

我正在自动化页面,这是我在 Python 中的第一次自动化。当我注册用户时它很好,但是当我尝试根据用户名和密码生成令牌时,它会给出上述类型错误。当我从 Python 2.7 更新到 3.5.1 时,此错误已开始出现。google了一下,发现是python 3的一个新特性,应该如何输入数据才能避免这个问题呢?我正在使用以下输入数据:

browser.find_element_by_id("username").send_keys("Worldmap")
browser.find_element_by_id("password").send_keys("hello")

以及以下生成密钥:

curl --user Worldmap:hello http://127.0.0.1:8080/api/auth/token

标签: pythontypeerrorincompatibletypeerror

解决方案


请参阅字符串编码和 unicode 解码方法。

string.encode('utf-8') 编码为 un​​icode 对象。

unicode.decode('utf-8') 从 unicode 对象解码。

>>> fred='astring'
>>> fred
'astring'
>>> fred.encode('utf-8')
b'astring'     
>>> bloggs=fred.encode('utf-8')
>>> bloggs
b'astring'
>>> bloggs.decode('utf-8')
'astring'

https://www.pythoncentral.io/encoding-and-decoding-strings-in-python-3-x/


推荐阅读