0

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'
2
  • Can you give us the full traceback? Commented Oct 30, 2013 at 12:00
  • Check if my solution worked for you. Commented Oct 30, 2013 at 12:07

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

after it run the catch will it still continue to run the code below? there are alot more codes below
Yes, it absolutely will.
Yea Worked, Thanks! btw it's Try Except, catch didnt work, i did a edit, hope this is useful for someone out there :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.