How to skip a tag when using Beautifulsoup find_all?

Question:

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 <span> elements.

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 <span> in find_all method?

Asked By: kyc12

||

Answers:

You can use .find_parent():

for tag in soup.find_all("span"):
    if tag.find_parent("table"):
        continue
    # we are not inside <table>
    # ...
Answered By: Andrej Kesely

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()

Answered By: psychicesp
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.