If-else – If found a value with bs4 … Else


I’m currently trying to do a mix between HTML and Python. My idea is:

If I find a value in this HTML:

   Then run this method


    Run this other method.

Basically I have

soup = soup(r.content, "lxml")
findKey = soup.find('div', {'class': 'TalkingHand'})['data-key']

so far and what I want to do is to make it like if I find a any value or this element in the HTML then I supposed to do a method inside my program which we can call MethodFound but if we don’t find this element in the HTML then we should do something else: we can call it DoNothing

I’m stuck at the if statement where I don’t really know where to start.

If(findKey == ..... <-- I dont know really)...
Asked By: WeInThis



You can catch the exception that bs4 will throw when the element is not there. Here is an example.

    soup = soup(r.content, "lxml")
    findKey = soup.find('div', {'class': 'TalkingHand'})['data-key']

    # Do stuff with the found key
except AttributeError:
    # Key wasn't found do stuff
Answered By: washcloth
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.