我正在try 将工作的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, 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.

我还读了另外两张票(ticket1ticket2),上面提到了日期编码.

当我把第f = urllib.request.urlopen(req)行改为f = urllib.request.urlopen(req.encode('utf-8'))行时,我收到了以下错误:AttributeError: 'Request' object has no attribute 'encode'

我一直在思考如何让Python 3代码工作.你能帮帮我吗?

推荐答案

docsNote 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-3.x相关问答推荐

我的SELECT函数搜索的是列,而不是列中的数据.我怎么才能让它搜索数据呢?

Numpy argmin()以查找最近的元组

切片时是否在NumPy ND数组中创建新对象?

无法使用Python发送带有参数和标头的POST请求

为什么我无法在django中按月筛选事件?

链接列未延伸到数据框的末尾

Pandas 转换为日期时间

TypeError: issubclass() arg 1 在 Flask 中导入 langchain 时必须是一个类

如何将多输入数据加载器传递给单输入模型

我应该如何调整我的变量,以便如果有任何单词符合其中的条件,程序会将其附加到新列表中?

在 groupby 之后,Pandas 在特定类别中获得最常见和最后的值

在python中将字符串写入文本文件

matplotlib.pyplot 多边形,具有相同的纵横比和紧凑的布局

Python ** 用于负数

TimescaleDB:是否可以从 Python 调用create_hypertable?

如何配置 Atom 以运行 Python3 脚本?

ImportError:无法导入名称cross_validate

使用 python2 和 python3 创建一个 virtualenv

计数大于Pandas groupby 中的值的项目

将列表列表转换为Python中的字典字典