1

is there a way to extract the below class if the whole class text = New

 <li class="ClassifiedDetail">New

tried:

doc.find('li', class_ = 'ClassifiedDetail').attrs['New']

maybe something like if class text = New or contains 'New', take it?

2
  • doc.find('li', class_ = 'ClassifiedDetail', text="New") may work Commented Jan 20, 2022 at 15:33
  • 1
    @JoseManueldeFrutos doesn't work, below is the answer why. thank you. Commented Jan 20, 2022 at 16:02

1 Answer 1

1

Note It is not that clear if you mean class or tag, so I assume you mean the text of a tag

One approach could be use of css selectors and :-soup-contains():

soup.select('li.ClassifiedDetail:-soup-contains("New")')

Alternativ is using string=re.compile(), cause stringor in former versionstext` works only for exact matches of full string:

soup.find_all('li', class_ = 'ClassifiedDetail',text=re.compile('New'))

Example

from bs4 import BeautifulSoup

html='''
<li class="ClassifiedDetail">New</li>
<li class="ClassifiedDetail">New York</li>
<li class="ClassifiedDetail">Ne </li>
<li class="ClassifiedDetail">Old</li>
<li class="ClassifiedDetail">knew</li>
'''

soup = BeautifulSoup(html)
for li in soup.select('li.ClassifiedDetail:-soup-contains("New")'):
    print(li.text)

Output

New
New York
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.