1

I am having following error when generating an Auth Token:

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

I am Automating a Page and this is my first ever Automation in Python. When I register a user it goes fine but when I try to generate a token based on user name and password it gives the above type error. This error has started to appear when I updated from Python 2.7 to 3.5.1. I have googled and found that it is a new feature in python 3. How should I enter the data to avoid this problem? I am using following to enter data:

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

and the following to generate key:

curl --user Worldmap:hello http://127.0.0.1:8080/api/auth/token
danronmoon
  • 3,814
  • 5
  • 34
  • 56
Sara
  • 181
  • 1
  • 3
  • 16
  • Add `b` just before opening quotes, making them `b"Worldmap"` and `b"hello"`. In Python2 the types were confusing because you didn't know whether you were dealing with bytes or ASCII string (and having to convert things into unicode strings sucked as well). Now the distinction is nice, but sometimes API calls require bytes objects or return those - like here. – h4z3 Dec 06 '19 at 15:31
  • Does this answer your question? [Python Convert String to Byte](https://stackoverflow.com/questions/40235855/python-convert-string-to-byte) – Jared Smith Dec 06 '19 at 15:32
  • @h4z3 I have tried what tyou suggested and it didnt work last night But I remember I tried something . b"Worldmap"followed by something. OK tried and got following error browser.find_element_by_id("username").send_keys(b"signantcl") File "C:\python-3.5.3\lib\site-packages\selenium\webdriver\remote\webelement.py", line 478, in send_keys {'text': "".join(keys_to_typing(value)), TypeError: sequence item 0: expected str instance, int found – Sara Dec 06 '19 at 15:38
  • Could you post full stacktrace of the original error (when you do str, not bytes)? Because it seems the string was ok (and I checked Selenium docs, it requires a string; and the error now says it requires a string, and iterating through bytes gives it ints), and the problem is somewhere around there, not **in** there! :o Some nearby code (e.g. how you init your `browser` etc.) could be useful as well. – h4z3 Dec 06 '19 at 15:55

1 Answers1

0

See the string encode, and unicode decode methods.

string.encode('utf-8') encodes to a unicode object.

unicode.decode('utf-8') decodes from a unicode object.

>>> 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/

Colin
  • 173
  • 1
  • 6