在我的應用程序中,用戶輸入一個URL,然後嘗試打開鏈接並獲取頁面標題。但是我意識到可能存在許多不同類型的錯誤,包括標題中的unicode字符或換行符,以及AttributeError
和IOError
。我第一次嘗試捕捉每個錯誤,但現在如果出現url提取錯誤,我想重定向到用戶將手動輸入標題的錯誤頁面。我如何捕獲所有可能的錯誤?這是我現在的代碼:如何通過網址抓取(python)捕獲所有可能的錯誤?
title = "title"
try:
soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url))
title = str(soup.html.head.title.string)
if title == "404 Not Found":
self.redirect("/urlparseerror")
elif title == "403 - Forbidden":
self.redirect("/urlparseerror")
else:
title = str(soup.html.head.title.string).lstrip("\r\n").rstrip("\r\n")
except UnicodeDecodeError:
self.redirect("/urlparseerror?error=UnicodeDecodeError")
except AttributeError:
self.redirect("/urlparseerror?error=AttributeError")
#https url:
except IOError:
self.redirect("/urlparseerror?error=IOError")
#I tried this else clause to catch any other error
#but it does not work
#this is executed when none of the errors above is true:
#
#else:
# self.redirect("/urlparseerror?error=some-unknown-error-caught-by-else")
UPDATE
正如我說try...except
一邊寫title
到數據庫中的意見建議由@Wooble:
try:
new_item = Main(
....
title = unicode(title, "utf-8"))
new_item.put()
except UnicodeDecodeError:
self.redirect("/urlparseerror?error=UnicodeDecodeError")
這工作。儘管外的範圍內的字符â€」
仍處於title
根據日誌記錄信息:
***title: 7.2. re â€」 Regular expression operations — Python v2.7.1 documentation**
你知道爲什麼嗎?
一個的UnicodeDecodeError幾乎可以肯定是因爲你的代碼不正確處理Unicode的,不會因爲用戶輸入無效數據。你應該修復你的應用程序來處理unicode。 – 2011-03-07 23:52:47