Python 3.x:urllib.request 错误
我的代码:
import urllib.request, urllib.parse, urllib.error
def login():
url = 'http://rsbot.lt/news.php'
values = {'user_name' : 'Name',
'user_pass' : 'Password' }
data = urllib.parse.urlencode(values)
req = urllib.request.Request(url, data)
response = urllib.request.urlopen(req)
return response.read()
login()
我的错误:
Traceback (most recent call last):
File "C:\Users\Myrez\Desktop\test.py", line 13, in <module>
login()
File "C:\Users\Myrez\Desktop\test.py", line 10, in login
response = urllib.request.urlopen(req)
File "C:\Python32\lib\urllib\request.py", line 138, in urlopen
return opener.open(url, data, timeout)
File "C:\Python32\lib\urllib\request.py", line 367, in open
req = meth(req)
File "C:\Python32\lib\urllib\request.py", line 1066, in do_request_
raise TypeError("POST data should be bytes"
TypeError: POST data should be bytes or an iterable of bytes. It cannot be str.
我尝试过编码,但没有帮助。
My code:
import urllib.request, urllib.parse, urllib.error
def login():
url = 'http://rsbot.lt/news.php'
values = {'user_name' : 'Name',
'user_pass' : 'Password' }
data = urllib.parse.urlencode(values)
req = urllib.request.Request(url, data)
response = urllib.request.urlopen(req)
return response.read()
login()
My error:
Traceback (most recent call last):
File "C:\Users\Myrez\Desktop\test.py", line 13, in <module>
login()
File "C:\Users\Myrez\Desktop\test.py", line 10, in login
response = urllib.request.urlopen(req)
File "C:\Python32\lib\urllib\request.py", line 138, in urlopen
return opener.open(url, data, timeout)
File "C:\Python32\lib\urllib\request.py", line 367, in open
req = meth(req)
File "C:\Python32\lib\urllib\request.py", line 1066, in do_request_
raise TypeError("POST data should be bytes"
TypeError: POST data should be bytes or an iterable of bytes. It cannot be str.
I've tried encode but it did not help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该错误告诉您做错了什么:
“TypeError:POST 数据应该是字节或可迭代的字节。它不能是 str。”
对于 POST 数据,您应该使用 bytes 类型,而不是 str 类型。
如果您通过执行
type(data)
查看数据类型,您会发现它是一个 str,但它应该是一个字节。如果您随后查看有关如何使用 urllib 的 Python 文档 ,您将看到如何发布表单的示例:
它告诉您如何将数据(此处称为 params)转换为字节而不是 str。
The error tells you what you are doing wrong:
"TypeError: POST data should be bytes or an iterable of bytes. It cannot be str."
You should use a bytes type, not a str type for the POST data.
If you look at your data type, by doing
type(data)
, you'll see that it is a str, but it should be a bytes.If you then look at the Python documentation on how to use urllib, you will see there the example of how to post a form:
Which tells you how to make the data (here called params) into bytes instead of str.