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 checkin list of divs if there is a span within with class 'new'

In Beautifulsoup i receive a list of divs. Each of these divs has an span included:

<div role="news_item" class="ni_nav_9tg">
   <span class="nav_element_new_S5g">Germany vs. Japan</span>
</div>
...
<div role="news_item" class="ni_nav_9tg">
   <span class="nav_element_new_S5g">Brasil vs. Serbia</span>
</div>

What i want is to check if in this list of div a span exist whose class contains string "new". Just true or false as result.

Of course i could iterate through each item div in list and get span item after this check if class contains string "new", but i am not sure if this is the right approach.

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 :

You could select them directly like:

soup.select('div[role="news_item"]:has(span[class*="new"])')

to get True or False check the len() of the ResultSet:

len(soup.select('div[role="news_item"]:has(span[class*="new"])')) > 0

Example

from bs4 import BeautifulSoup
html='''
<div role="news_item" class="ni_nav_9tg">
   <span class="nav_element_new_S5g">Germany vs. Japan</span>
</div>
...
<div role="news_item" class="ni_nav_9tg">
   <span class="nav_element_new_S5g">Brasil vs. Serbia</span>
</div>
'''

soup = BeautifulSoup(html)

len(soup.select('div[role="news_item"]:has(span[class*="new"])')) > 0
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