Python 3中的urllib产生类型错误:POST数据应该是字节或字节的可迭代。 它不能是类

2019-05-12 04:24发布

我想工作的Python 2.7的代码转换成Python 3码,我从urllib的请求模块接收类型的错误。

我用的是内置的Python 2to3的工具,下面的工作urllib而urllib2的Python 2.7版代码转换:

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()

从2to3的模块的输出是下面的Python代码3:

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()

当运行的Python代码3产生以下错误:

---------------------------------------------------------------------------
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         for 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 be bytes or an iterable of bytes. " \
   1111                       "It cannot be of type str."
-> 1112                 raise TypeError(msg)
   1113             if not request.has_header('Content-type'):
   1114                 request.add_unredirected_header(

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

我也看过其他的两张门票( ticket1和ticket2里面提到编码的日期)。

当我改变了线f = urllib.request.urlopen(req)f = urllib.request.urlopen(req.encode('utf-8'))我收到以下错误: AttributeError: 'Request' object has no attribute 'encode'

我坚持就如何使Python的3码的工作。 请你帮助我好吗?

Answer 1:

从文档 请注意,从PARAMS进行urlencode被编码为字节输出被发送到的urlopen作为数据之前:

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)


Answer 2:

试试这个:

url = 'https://www.customdomain.com'
d = dict(parameter1="value1", parameter2="value2")

f = urllib.parse.urlencode(d)
f = f.encode('utf-8')

req = urllib.request.Request(url, f)

你的问题就出在你处理词典的方式。



文章来源: Python 3 urllib produces TypeError: POST data should be bytes or an iterable of bytes. It cannot be of type str