簡體   English   中英

捕獲異常,運行替代代碼並繼續使用Line Python

[英]Catch Exception , Run Alternative Code & Continue from Line Python

我目前正在使用Selenium和BeautifulSoup來提取數據,有時候不同頁面的格式可能略有不同,最多3種不同類型的html差異,當它來到不同的頁面之一時,我無法幫助它它給了我一個例外,因為數據不存在。

我可以執行類似Exception = AttributeError的操作,嘗試此代碼並從停止的位置繼續嗎?

AttributeError: 'NoneType' object has no attribute 'text'

這是當前的代碼

  price = soup.find('li', {'id' :'J_PromoPrice'})
        priced = price.find('strong', {'class' :'tb-rmb-num'}).text
        if priced == "":
           priced = price.find('strong', {'class' :'tb-rmb-num'}).text
        else:
           print ("No Normal Price Found")

正如你所看到的,已經存在一組IF ELSE來檢測它是否為空,如果為空=找到另一個標簽用於處理2種不同類型的html的文本,但是第3個我正面臨問題的是它沒有甚至沒有TAG,但確實有它在其他地方。

簡而言之,我正試圖從其他地方獲取文本,如果我點擊此異常然后繼續腳本從異常被打在我臉上。

更新完整跟蹤

Traceback (most recent call last):
  File "C:\Users\X\Desktop\Python\python.py", line 521, in <module>
    getLoadItem()
  File "C:\Users\X\Desktop\Python\python.py", line 57, in getLoadItem
    getLoadItemAnalyse(loop['ID'],loop['Link'])
  File "C:\Users\X\Desktop\Python\python.py", line 236, in getLoadItemAnalyse
    priced = price.find('strong', {'class' :'tb-rmb-num'}).text
AttributeError: 'NoneType' object has no attribute 'text'

您可以使用try/except塊。

例如:

price = soup.find('li', {'id' :'J_PromoPrice'})
try:
    priced = price.find('strong', {'class' :'tb-rmb-num'}).text
    if priced == "":
        priced = price.find('strong', {'class' :'tb-rmb-num'}).text
    else:
        print ("No Normal Price Found")
except AttributeError:
     # Try this code instead

這基本上意味着,“好的嘗試這個代碼,它可能會搞砸”,在這種情況下,在catch塊下面做什么。

暫無
暫無

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

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