Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BeautifulSoup, change specific style attribut

I want to change only the background-color style with BeautifulSoup :

My html :

<td style="font-size: .8em; font-family: monospace; background-color: rgb(244, 244, 244);">
</td>

I would like to do something like this :

soup_td = BeautifulSoup(html_td, "html.parser")
soup_td.td["style"]["background-color"] = "red;"
like image 411
Dbi Avatar asked Dec 23 '22 11:12

Dbi


2 Answers

That's a rather complicated answer above; you can also just do this:

for tag in soup.findAll(attrs={'class':'example'}):
    tag['style'] = "color: red;"

Combine the soup.findAll with whatever selector of BeautifulSoup you'd like to use.

like image 175
IAspireToBeGladOS Avatar answered Dec 26 '22 00:12

IAspireToBeGladOS


Use cssutils to manipulate CSS, like this:

from bs4 import BeautifulSoup
from cssutils import parseStyle

html = '<td style="font-size: .8em; font-family: monospace; background-color: rgb(244, 244, 244);"></td>'

# Create soup from html
soup = BeautifulSoup(html, 'html.parser')

# Parse td's styles
style = parseStyle(soup.td['style'])

# Change 'background-color' to 'red'
style['background-color'] = 'red'

# Replace td's styles in the soup with the modified styles
soup.td['style'] = style.cssText

# Outputs: <td style="font-size: .8em; font-family: monospace; background-color: red"></td>
print(soup.td)

You could also use regex if you're comfortable with using it.

like image 40
Omar Einea Avatar answered Dec 25 '22 23:12

Omar Einea