Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to skip a tag when using Beautifulsoup find_all?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading