Home > Mobile >  How to skip a tag when using Beautifulsoup find_all?
How to skip a tag when using Beautifulsoup find_all?

Time:11-23

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?

CodePudding user response:

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

CodePudding user response:

You can use .find_parent():

for tag in soup.find_all("span"):
    if tag.find_parent("table"):
        continue
    # we are not inside <table>
    # ...
  • Related