我正试图从网页上抓取一些信息,这些信息与信息的位置不一致.我有代码来处理各种可能性; 我想要的是按顺序尝试它们,然后如果它们都不起作用我想优雅地失败并继续前进.
也就是说,在伪代码中:
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"
Run Code Online (Sandbox Code Playgroud)
我可以使用嵌套的try语句执行此操作,但如果我需要15种可能性尝试,那么我将需要15级缩进!
这似乎是一个微不足道的问题,我觉得我错过了什么,但我已经搜索到了地面,找不到任何看起来与这种情况相同的东西.有没有合理的Pythonic方式来做到这一点?
编辑:由于John的(相当不错)解决方案在下面提出,为简洁起见,我将上面的每个查找都写成单个函数调用,而实际上它通常是一小块BeautifulSoup调用,例如soup.find('h1', class_='parselikeHeader').当然,我可以将它们包装在函数中,但是这些简单的块看起来有点不雅 - 如果我的速记改变了问题,那就道歉了.
这可能是一个更有用的插图:
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"
Run Code Online (Sandbox Code Playgroud)