Trying to figure out how to keep my script running if a value isn't found.
Here's a snippet of my code:
html = "my.html"
get_data = open(html,'r').read()
soup = BeautifulSoup(get_data, "lxml")
title = soup.find_all("tr", {"class":"clock-seg on-clock paid"})[-1]
Then I do stuff with the "title" variable once the data is found. If that specific item isn't found in the HTML fileS, I get this:
Traceback (most recent call last):
File "fclm.py", line 40, in <module>
title = soup.find_all("tr", {"class":"clock-seg on-clock paid"})[-1]
IndexError: list index out of range
The code snippet above is in a loop so it's going through multiple HTML files. If I have an empty one, I just want it to keep going and not return an error.
Use a try-except
block
Ex:
html = "my.html"
get_data = open(html,'r').read()
soup = BeautifulSoup(get_data, "lxml")
try:
title = soup.find_all("tr", {"class":"clock-seg on-clock paid"})[-1]
except IndexError:
pass
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.