如何通过url fetch(python)捕获所有可能的错误?
在我的应用程序中,用户输入一个URL,我尝试打开该链接并获取该页面的标题。但我意识到可能存在许多不同类型的错误,包括标题中的unicode字符或换行符以及
AttributeError
和IOError
。我首先尝试捕获每个错误,但现在如果出现url fetch错误,我想重定向到错误页面,用户将手动输入标题。如何捕获所有可能的错误?这是我现在的代码:
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("rn").rstrip("rn")
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
正如@Wooble在评论中所建议的,我在将title
写入数据库时添加了try...except
:
try:
new_item = Main(
....
title = unicode(title, "utf-8"))
new_item.put()
except UnicodeDecodeError:
self.redirect("/urlparseerror?error=UnicodeDecodeError")
这有效。根据记录信息,虽然超出范围的字符ѭ6仍然在title
:
***title: 7.2. re — Regular expression operations — Python v2.7.1 documentation**
你知道为什么吗?
没有找到相关结果
已邀请:
2 个回复
河饶办斜施
最后一个除了将捕获之前未捕获的任何异常(即不是IOError或ValueError的异常。)
念炯