![](/img/trans.png)
[英]Need help adapting a Python 3.x script to run under Python 2.7 (urllib.request & urllib.parse)
[英]Python 3.x: urllib.request error
我的代碼:
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.
我試過編碼,但沒有幫助。
該錯誤告訴您您做錯了什么:
“TypeError:POST 數據應該是字節或字節的可迭代。它不能是 str。”
您應該對 POST 數據使用 bytes 類型,而不是 str 類型。 如果您通過執行type(data)
查看您的數據類型,您會看到它是一個 str,但它應該是一個字節。
如果您然后查看有關如何使用 urllib 的 Python 文檔,您將在那里看到如何發布表單的示例:
>>> import urllib.request
>>> import urllib.parse
>>> params = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>> params = params.encode('utf-8')
>>> f = urllib.request.urlopen("http://www.musi-cal.com/cgi-bin/query", params)
它告訴您如何將數據(此處稱為參數)轉換為字節而不是 str。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.