Python 3 urllib produces TypeError: POST data should be bytes or an iterable of bytes. It cannot be of type str -
i trying convert working python 2.7 code python 3 code , receiving type error urllib request module.
i used inbuilt 2to3 python tool convert below working urllib , urllib2 python 2.7 code:
import urllib2 import urllib url = "https://www.customdomain.com" d = dict(parameter1="value1", parameter2="value2") req = urllib2.request(url, data=urllib.urlencode(d)) f = urllib2.urlopen(req) resp = f.read()
the output 2to3 module below python 3 code:
import urllib.request, urllib.error, urllib.parse url = "https://www.customdomain.com" d = dict(parameter1="value1", parameter2="value2") req = urllib.request.request(url, data=urllib.parse.urlencode(d)) f = urllib.request.urlopen(req) resp = f.read()
when python 3 code run following error produced:
--------------------------------------------------------------------------- typeerror traceback (most recent call last) <ipython-input-56-206954140899> in <module>() 5 6 req = urllib.request.request(url, data=urllib.parse.urlencode(d)) ----> 7 f = urllib.request.urlopen(req) 8 resp = f.read() c:\users\admin\anaconda3\lib\urllib\request.py in urlopen(url, data, timeout, cafile, capath, cadefault, context) 159 else: 160 opener = _opener --> 161 return opener.open(url, data, timeout) 162 163 def install_opener(opener): c:\users\admin\anaconda3\lib\urllib\request.py in open(self, fullurl, data, timeout) 459 processor in self.process_request.get(protocol, []): 460 meth = getattr(processor, meth_name) --> 461 req = meth(req) 462 463 response = self._open(req, data) c:\users\admin\anaconda3\lib\urllib\request.py in do_request_(self, request) 1110 msg = "post data should bytes or iterable of bytes. " \ 1111 "it cannot of type str." -> 1112 raise typeerror(msg) 1113 if not request.has_header('content-type'): 1114 request.add_unredirected_header( typeerror: post data should bytes or iterable of bytes. cannot of type str.
i have read 2 other tickets (ticket1 , ticket2) mentioned encoding date.
when changed line f = urllib.request.urlopen(req)
f = urllib.request.urlopen(req.encode('utf-8'))
received following error: attributeerror: 'request' object has no attribute 'encode'
i stuck how make python 3 code work. please me?
from docs note params output urlencode encoded bytes before sent urlopen data:
data = urllib.parse.urlencode(d).encode("utf-8") req = urllib.request.request(url) urllib.request.urlopen(req,data=data) f: resp = f.read() print(resp)
Comments
Post a Comment