2012-05-03 58 views
2

我知道如何使用python從web下載文件,但是我希望處理所請求文件不存在的情況。在這種情況下,我想打印一條錯誤消息(「404:找不到文件」)並且不向磁盤寫入任何內容。但是,我仍然希望能夠繼續執行該程序(即,下載可能存在的列表中的其他文件)。Python:使用urllib下載不存在的文件時處理異常

我該怎麼做?下面是一些模板代碼,用於下載給定其URL的文件(如果您認爲有更好的方法,隨意修改它,但請保持簡潔和簡潔)。

import urllib 
urllib.urlretrieve ("http://www.example.com/myfile.mp3", "myfile.mp3") 

回答

0
from urllib2 import URLError 

try: 
    # your file request code here 
except URLError, e: 
    if e.code == 404: 
     # your appropriate code here 
    else: 
     # raise maybe? 

我跟着this指南,其中有一個特定的section about handling exceptions,並發現它真的很有幫助。

-1

您的代碼應該是這樣的:

try: 
    urllib.urlretrieve ("http://www.example.com/myfile.mp3", "myfile.mp3") 
except URLError,e: 
    if e.code==404: 
     print 'file not found. moving on...' 
     pass 
+2

從我可以告訴,urllib.urlretrieve將不會在404響應養URLError。如果域名不好,則會引發IOError。否則'myfile.mp3'將只包含html 404響應。 – johncip

-1
import urllib, urllib2 
try: 
    urllib.urlretrieve ("http://www.example.com/", "myfile.mp3") 
except URLError, e: 
    if e.code == 404: 
     print "4 0 4" 
    else: 
     print "%s" % e 

這是你的代碼做什麼。它基本上試圖檢索www.example.com的網頁並將其寫入myfile.mp3。它不會結束異常,因爲它不查找myfile.mp3,它基本上將它獲得的所有內容寫入到myfile.mp3中

如果您正在查找代碼以在Web上的某個位置下載文件,試試這個

How do I download a zip file in python using urllib2?

+1

你無法捕捉到錯誤 – timger