我不太明白如何在 Python 中正确使用异常。我想处理我不能完全信任的数据(它们很容易发生变化,如果发生变化,脚本可能会中断)。假设我使用 BeautifulSoup 处理网页。如果网站作者对其网站进行了一些更改,则某些声明可能会出现异常。让我们看一下这个代码示例:
data = urllib2.urlopen('http://example.com/somedocument.php').read()
soup = BeautifulSoup(data, convertEntities="html")
name = soup.find('td', text=re.compile(r'^Name$')).parent.nextSibling.string
print name
现在,如果 soup.find()
失败,因为该网站的所有者将更改网站的内容并将单元格 Name
重命名为 Names
,将引发异常 AttributeError: 'NoneType' object has no attribute 'parent'
。但我不介意!我希望某些数据不可用。我只想继续并使用我可用的变量(当然会有一些我需要的数据,如果它们不可用,我将直接退出。
我想出的唯一解决方案是:
try: name = soup.find('td', text=re.compile(r'^Name$')).parent.nextSibling.string
except AttributeError: name = False
try: email = soup.find('td', text=re.compile(r'^Email$')).parent.nextSibling.string
except AttributeError: email = False
try: phone = soup.find('td', text=re.compile(r'^Phone$')).parent.nextSibling.string
except AttributeError: phone = False
if name: print name
if email: print email
if phone: print phone
有没有更好的方法,或者我应该继续对每个类似的语句进行 try-except ?它看起来一点也不好看。
编辑:对我来说最好的解决方案是这样的:
try:
print 'do some stuff here that may throw and exception'
print non_existant_variable_that_throws_an_exception_here
print 'and few more things to complete'
except:
pass
这会很棒,但是 pass
将跳过 try
代码块中的任何内容,因此 and few more things to complete
永远不会被打印出来.如果有类似 pass 的东西,但是它会忽略错误并继续执行,那就太好了。
最佳答案
首先,如果你不介意这个异常,你可以让它通过:
try:
something()
except AttributeError:
pass
但永远不要这样做,因为它会让所有错误通过:
try:
something()
except Exception:
pass
至于你的代码示例,也许可以用这样的东西来整理:
myDict = {}
for item in ["Name", "Email", "Phone"]:
try:
myDict[item] = soup.find('td', text=re.compile(r'^%s$' % item)).parent.nextSibling.string
except Attribute
myDict[item] = "Not found"
for item in ["Name", "Email", "Phone"]:
print "%s: %s" % (item, myDict[item])
关于python - 如何正确处理异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6104167/