Hey.

I am trying to send a request with the necessary data to the form handler using the POST method.

data = { 'user': 'user', 'pass': 'pass'} dataToReq = urllib.parse.urlencode(data) request = urllib.request.Request('http://example.ru/login.php?', dataToReq) page = urllib.request.urlopen(request) 

The last line gives the error "TypeError: POST data should be bytes or an iterable of bytes. It cannot be be str". But if you convert dataToReq to bytes, then the handler does not seem to work with this data. In the examples, there is also no need to convert to bytes. How can this problem be solved?

  • Why question mark in url? - alexlz

1 answer 1

Badly read the documentation: 20.5. urllib.request - Extensible library for opening URLs

If there is no such data, it is necessary.

 >>> import urllib.request >>> req = urllib.request.Request(url='https://localhost/cgi-bin/test.cgi', ... data=b'This data is passed to stdin of the CGI') >>> f = urllib.request.urlopen(req) >>> print(f.read().decode('utf-8')) Got Data: "This data is passed to stdin of the CGI" 
  • Everything is wonderful and wonderful. Put 3.2 to check reluctance, but on the docks: the given excerpt from the description of urlopen. And for the class urllib.urlrequest.Request, black in English data may be a string specifying additional data to send to the server, or None if no such data is needed. - alexlz
  • If you convert to bytes, the data is sent, but the form remains empty and the page with this form is returned to me. What am I doing wrong here? Or can this page be sent to me for some other reason? - Olegas
  • one
    @alexlz, it means an error in the documentation, since This is the same thing in essence. It uses the banal isinstance check: def open (self, fullurl, data = None, timeout = socket._GLOBAL_DEFAULT_TIMEOUT): # accept a URL or a request object if isinstance (fullurl, str): req = Request (fullurl, data) : req = fullurl if data is not None: req.data = data @Olegas, dump the request and see what kind of request it comes. - Ilya Pirogov
  • @Olegas Well, do as the python asks. Do not hurt request = urllib.request.Request('http://example.ru/login.php', dataToReq.encode()) . Well, the fact that example.ru user user with a password pass will send to hell, so this is another story. - alexlz