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

Time:11-26

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

<div role="news_item" >
   <span >Germany vs. Japan</span>
</div>
...
<div role="news_item" >
   <span >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.

CodePudding user response:

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" >
   <span >Germany vs. Japan</span>
</div>
...
<div role="news_item" >
   <span >Brasil vs. Serbia</span>
</div>
'''

soup = BeautifulSoup(html)

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