Python尝试/除了:尝试多个选项 [英] Python try/except: trying multiple options
问题描述
我正在尝试从与信息位置不一致的网页上删除一些信息。我有代码来处理几种可能性;我想要的是按顺序尝试它们,那么如果没有一个工作,我想要优雅地失败并继续前进。
I'm trying to scrape some information from webpages that are inconsistent about where the info is located. I've got code to handle each of several possibilities; what I want is to try them in sequence, then if none of them work I'd like to fail gracefully and move on.
就是说,在伪代码中:
That is, in psuedo-code:
try:
info = look_in_first_place()
otherwise try:
info = look in_second_place()
otherwise try:
info = look_in_third_place()
except AttributeError:
info = "Info not found"
我可以使用嵌套的try语句来做到这一点,但是如果我需要15种可能性,那么我需要15个级别的缩进!
I could do this with nested try statements, but if I need 15 possibilities to try then I'll need 15 levels of indentation!
这似乎是一个琐碎的问题,我觉得我错过了一些东西,但是我已经搜索到了地面,找不到与这种情况相当的任何东西。有没有一个明智的和Pythonic的方式来做到这一点?
This seems like a trivial enough question that I feel like I'm missing something, but I've searched it into the ground and can't find anything that looks equivalent to this situation. Is there a sensible and Pythonic way to do this?
编辑:正如约翰(相当不错的)下面的解决方案提出来的,为了简洁起见,我把每个查找都写成一个单一的函数调用,而实际上通常是一小块BeautifulSoup调用,例如 soup.find('h1',class _ ='parselikeHeader')
。当然,我可以把它们包含在这些函数中,但是这似乎有点不合适 - 如果我的速记改变了问题,那么道歉。
As John's (pretty good) solution below raises, for brevity I've written each lookup above as a single function call, whereas in reality it's usually a small block of BeautifulSoup calls such as soup.find('h1', class_='parselikeHeader')
. Of course I could wrap these in functions, but it seems a bit inelegant with such simple blocks -- apologies if my shorthand changes the problem though.
这可能是一个更多的有用的说明:
This may be a more useful illustration:
try:
info = soup.find('h1', class_='parselikeHeader').get('href')
if that fails try:
marker = soup.find('span', class_='header')
info = '_'.join(marker.stripped_strings)
if that fails try:
(other options)
except AttributeError:
info = "Info not found"
推荐答案
如果每个查找是一个单独的函数,您可以将所有函数存储在列表中,然后逐个迭代。
If each lookup is a separate function, you can store all the functions in a list and then iterate over them one by one.
lookups = [
look_in_first_place,
look_in_second_place,
look_in_third_place
]
info = None
for lookup in lookups:
try:
info = lookup()
# exit the loop on success
break
except AttributeError:
# repeat the loop on failure
continue
# when the loop is finished, check if we found a result or not
if info:
# success
else:
# failure
这篇关于Python尝试/除了:尝试多个选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!