I want to edit an HTML document and parse some text using Beautifulsoup. I’m interested in
<span> tags but the ones that are NOT inside a
<table> element. I want to skip all tables when finding the
I’ve tried to find all
<span> elements first and then filter out the ones that have
<table> in any parent level. Here is the code. But this is too slow.
for tag in soup.find_all('span'): ancestor_tables = [x for x in tag.find_all_previous(name='table')] if len(ancestor_tables) > 0: continue text = tag.text
Is there a more efficient alternative? Is it possible to ‘hide’ / skip tags while searching for
You can use
for tag in soup.find_all("span"): if tag.find_parent("table"): continue # we are not inside <table> # ...
The way I would approach this would be to simply remove all tables from the html before doing my find_all on span.
Here is a thread I found on removing tables. I like the accepted answer because .extract() gives you the opportunity to capture the removed tables, though .decompose() would be better if you don’t care about anything in the tables.
Here is the code from this answer:
for table in soup.find_all("table"): table.extract()