Python error: Type error: POST data should be bytes; also user-agent issue

前端 未结 2 662
余生分开走
余生分开走 2020-12-18 23:25

Using the following code I received an error:

TypeError: POST data should be bytes or an iterable of bytes. It cannot be str

Second concern

2条回答
  •  旧巷少年郎
    2020-12-19 00:17

    data = urllib.parse.urlencode(values)
    type(data) #this returns . it's a string
    

    The urllib docs say for urllib.request.Request(url, data ...):

    The urllib.parse.urlencode() function takes a mapping or sequence of 2-tuples and returns a string in this format. It should be encoded to bytes before being used as the data parameter. etc etc

    (emphasis mine)

    So you have a string that looks right, what you need is that string encoded into bytes. And you choose the encoding.

    binary_data = data.encode(encoding)
    

    in the above line: encoding can be 'utf-8' or 'ascii' or a bunch of other things. Pick whichever one the server expects.

    So you end up with something that looks like:

    data = urllib.parse.urlencode(values)
    binary_data = data.encode(encoding) 
    req = urllib.request.Request(url, binary_data)
    

提交回复
热议问题