2015-11-10 50 views
0

我在python 3.5中有以下代碼。在python中打開Url的錯誤

import urllib.request 

prof_list = open(r"C:\local\profanity.txt") 
contents = prof_list.read() 
connect = urllib.request.urlopen("http://wdyl.com/profanity?q="+contents) 
output = connect.read() 
connect.close() 
prof_list.close() 

當我運行的代碼,我得到

raise HTTPError(req.full_url, code, msg, hdrs, fp) 
urllib.error.HTTPError: HTTP Error 400: Bad Request 

雖經多方努力,未能身影。

+0

是什麼profanity.txt的內容? –

回答

1

你需要一個額外的參數傳遞給urllib.request.urlopen像顯示在下面的例子:

urllib.request.urlopen('someurl.com', data=None) # if you have extra data to send to the server 

請看一看這個PAGE多瞭解不同的信息發送到服務器。

+0

我試過這個,但仍然有錯誤的請求錯誤。 – Main

0

在使用它之前,您需要對查詢字符串進行編碼。

from urllib.parse import quote 
encoded_query=quote(query) 

然後你可以使用

urllib.request.urlopen("http://wdyl.com/profanity?q="+encoded_query)