微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python 3 urllib产生TypeError:POST数据应为字节或字节可迭代不能是str类型

如何解决Python 3 urllib产生TypeError:POST数据应为字节或字节可迭代不能是str类型

From thedocs Note that params output from urlencode is encoded to bytes before it is sent to urlopen as data:

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)

解决方法

我正在尝试将有效的Python 2.7代码转换为Python 3代码,并且从urllib请求模块收到类型错误。

我使用内置的2to3 Python工具来转换以下工作的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,timeout)
    162 
    163 def install_opener(opener):

C:\Users\Admin\Anaconda3\lib\urllib\request.py in open(self,fullurl,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代码工作感到困惑。请你帮助我好吗?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。