在我的应用程序中,用户输入一个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