2013-05-17 13 views
0

請能有人將以下內容從python2轉換爲python3;在python 3中提交一個web表單

import requests 

url = "http://duckduckgo.com/html" 
payload = {'q':'python'} 
r = requests.post(url, payload) 
with open("requests_results.html", "w") as f: 
f.write(r.content) 

我得到了;

Traceback (most recent call last): 
File "C:\temp\Python\testFile.py", line 1, in <module> 
import requests 
ImportError: No module named 'requests' 

我也試過了;

import urllib.request 

url = "http://duckduckgo.com/html" 
payload = {'q':'python'} 
r = urllib.request.post(url, payload) 
with open("requests_results.html", "w") as f: 
f.write(r.content) 

,但我得到

Traceback (most recent call last): 
File "C:\temp\Python\testFile.py", line 5, in <module> 
r = urllib.request.post(url, payload) 
AttributeError: 'module' object has no attribute 'post' 
+0

你碰上你做了Python 3中,當什麼問題? –

+0

此, 回溯(最近通話最後一個): 文件 「C:\ TEMP \ Python的\ testFile.py」,1號線,在 導入請求 導入錯誤:沒有模塊名爲 '請求' – Scott

+1

你*安裝* Python 3的'請求'?它不是標準庫(在Python 2 *或* 3中)。 –

回答

0

所以,在python3.2,r.content是一個字節串,而不是一個海峽,並寫不喜歡它。你可能想r.text改用:

with open("requests_results.html", "w") as f: 
    f.write(r.text) 

你可以看到它的請求文件中http://docs.python-requests.org/en/latest/api.html#main-interface

class requests.Response 
    content - Content of the response, in bytes. 
    text - Content of the response, in unicode. if Response.encoding is None and chardet  module is available, 

encoding will be guessed.

編輯:

我看到經過編輯的問題之前公佈。是的,就像Martijn Pieters說的那樣,你需要安裝python3的請求模塊才能導入它。

+0

這絕對不是這裏的問題。 – mata

+0

是的,原來的問題沒有指定實際的錯誤。 – Neurogeek

+0

在python3中提交web表單的最簡單方法是什麼? – Scott

0

我認爲這裏的問題是沒有安裝Requests軟件包。或者,如果你已經安裝了它,它已經安裝在你的python2.x目錄中,而不是在python3中,所以你不能使用請求模塊。嘗試將python3作爲默認副本,然後安裝請求。

也可以嘗試訪問該article邁克爾Foord它幫助您使用urlib2的所有功能

+0

當然,不要忘記[python文檔](http://docs.python.org/2/library/urllib2.html)瞭解更多信息 – Ankit