How to checkin list of divs if there is a span within with class 'new'

Question:

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.

Asked By: STORM

||

Answers:

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
Answered By: HedgeHog