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
q5858255 回答:Python:具有TypeError:需要一个类似字节的对象,而不是生成令牌时的'str'

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

string.encode('utf-8')编码为unicode对象。

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/

本文链接:https://www.f2er.com/2961838.html

大家都在问