之前一直使用python2版本的urllib进行请求操作,虽然已经对下面的代码进行了修改,但是报错:TypeError: POST data should be bytes or an iterable of bytes. It cannot be of type str
urllib.urlencode() => urllib.parse.urlencode()
urllib.urlopen() => urllib.request.urlopen()
'''
对
修改前
import urllib2 import urllib
url = "https://www.xxx.com" d = dict(parameter1="value1", parameter2="value2")
req = urllib2.Request(url, data=urllib.urlencode(d)) f = urllib2.urlopen(req) resp = f.read() ...
修改后
import urllib.request, urllib.parse
url = "https://www.xxx.com" d = dict(parameter1="value1", parameter2="value2")
data = urllib.parse.urlencode(d).encode("utf-8") req = urllib.request.Request(url) with urllib.request.urlopen(req,data=data) as f: resp = f.read() print(resp) ... ```