If-else – If found a value with bs4 … Else
Question:
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
Else:
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)...
Answers:
You can catch the exception that bs4 will throw when the element is not there. Here is an example.
try:
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
pass
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
Else:
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)...
You can catch the exception that bs4 will throw when the element is not there. Here is an example.
try:
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
pass