简体   繁体   中英

Catch Exception , Run Alternative Code & Continue from Line Python

I'm currently using Selenium & BeautifulSoup to extract data , sometimes the format for different pages might be slightly different, at most max 3 different type of html difference, when it came to one of the different page, i couldn't help it as it gave me an exception because the data isnt there.

Can i do something like if Exception = AttributeError, try this code and continue from where it stopped?

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

This is the current code

  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")

As you can see , there is already a set of IF ELSE to detect if it's empty , if empty = find another tag for text that will handle 2 different type of html but the 3rd one which i'm facing an issue is that it doesn't even have the TAG but it does have it somewhere else.

In short, i'm trying to Grab text from somewhere else if i hit this exception then continue the script from where the exception was slapped in my face.

Update Full Trace

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'

You can use a try/except block.

So for example:

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

This basically means, "Okay try this code, and it might mess up", in that case, do whats underneath the catch block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM