I have something similar using BeautifulSoup:
for line in lines:
code = l.find('span', {'class':'boldHeader'}).text
coded = l.find('div', {'class':'Description'}).text
definition = l.find('ul', {'class':'definitions'}).text
print code, coded, def
However, not all elements always exist. I can conclude this in an attempt, except that it does not interrupt the execution of the program as follows:
for line in lines:
try:
code = l.find('span', {'class':'boldHeader'}).text
coded = l.find('div', {'class':'Description'}).text
definition = l.find('ul', {'class':'definitions'}).text
print code, coded, def
except:
pass
But how do I execute statements in a greedy way? For example, if only two elements are available codeand coded, I just want to get them and continue execution. At the moment, even if codethey codedexist, if they defdo not exist, the print command will never be executed.
One way to do this is to put try...exceptfor each statement like this:
for line in lines:
try:
code = l.find('span', {'class':'boldHeader'}).text
except:
pass
try:
coded = l.find('div', {'class':'Description'}).text
except:
pass
try:
definition = l.find('ul', {'class':'definitions'}).text
except:
pass
print code, coded, def
But this is an ugly approach, and I need something cleaner. Any suggestions?