Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using BeautifulSoup how do I remove a single class from an element with multiple classes?

I'm looking to remove a single class name from an element that has multiple class names, something like this:

<li class="name1 name2 name3">
    <a href="http://www.somelink.com">link</a>
</li>

I can use BeautifulSoup to remove classes in the following way:

soup.find(class_="name3")["class"] = ""

But this removes all classes not only the class that I want to lose.

like image 505
AndrewRM Avatar asked Oct 20 '25 09:10

AndrewRM


2 Answers

From your html, you can see,

 print soup.find(class_="name3").attrs
 {'class': ['name1', 'name2', 'name3']}

So, soup.find(class_="name3")['class'] returns nothing but a list. And you can remove element from it as you can remove elements from list. like,

soup.find(class_="name3")["class"].remove('name1')

This will remove the class that you want to lose.

like image 91
salmanwahed Avatar answered Oct 21 '25 21:10

salmanwahed


You could use a generator expression to rebuild the class names you want to keep

s = 'name1 name2 name3'
s = ' '.join(i for i in s.split() if i != 'name3')

>>> s
'name1 name2'
like image 26
Cory Kramer Avatar answered Oct 21 '25 22:10

Cory Kramer



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!