Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude data from tag

I want to exclude a specific text inside an html span tag. In the given example below I just wanted to fetch all test2 text from span with class under a-list-item.

my code:

<span class="a-list-item">test1</span>
<span class="a-list-item">test2</span>
<span class="a-list-item">test2</span>

my code: tag = tag.find_all("span", {"class" : "a-list-item"})

How to get all test2 only. Thanks for your response

like image 396
Gian Franco Tan Avatar asked Aug 01 '26 17:08

Gian Franco Tan


1 Answers

It looks like you are using Beautiful Soup. In Beautiful Soup 4.7+, this is easy to do just by using select instead of find_all. You can use :contains() wrapped in :not() to exclude spans that contain specific text.

from bs4 import BeautifulSoup
markup = '''
<span class="a-list-item">test1</span> 
<span class="a-list-item">test2</span> 
<span class="a-list-item">test2</span>
'''
soup = BeautifulSoup(markup)
print(soup.select("span.a-list-item:not(:contains(test1))"))

Output

[<span class="a-list-item">test2</span>, <span class="a-list-item">test2</span>]
like image 109
facelessuser Avatar answered Aug 04 '26 07:08

facelessuser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!