簡體   English   中英

Python嘗試/除了:嘗試多個選項

[英]Python try/except: trying multiple options

我正試圖從網頁上抓取一些信息,這些信息與信息的位置不一致。 我有代碼來處理各種可能性; 我想要的是按順序嘗試它們,然后如果它們都不起作用我想優雅地失敗並繼續前進。

也就是說,在偽代碼中:

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級縮進!

這似乎是一個微不足道的問題,我覺得我錯過了什么,但我已經搜索到了地面,找不到任何看起來與這種情況相同的東西。 有沒有合理的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"

如果每個查找都是一個單獨的函數,則可以將所有函數存儲在列表中,然后逐個迭代它們。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM