Python错误:TypeError:POST数据应为字节
在我下面的代码中,我遇到了一个错误:“raise TypeError("POST data should be bytes" TypeError: POST data should be bytes or an iterable of bytes. It cannot be str.”
我哪里做错了呢?我使用的是Python 3.2.2。
下面是代码:
msg = "Test post"
password_manager = urllib.request.HTTPPasswordMgr()
password_manager.add_password("Twitter API",
"http://twitter.com/statuses", "sampleusername", "password")
http_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
page_opener = urllib.request.build_opener(http_handler)
urllib.request.install_opener(page_opener)
params = urllib.parse.urlencode( {'status':msg} )
resp = urllib.request.urlopen("http://twitter.com/statuses/update.json", params)
resp.read()
1 个回答
3
这句话的意思很简单——在Python 3中,字符串默认是unicode格式的,但你不能直接使用unicode格式的字符串;你需要用字节字符串(bytestring)。
下面的代码应该可以正常工作:
msg = b"Test post"