BeautifulSoup,更改特定的样式属性

Dbi*_*Dbi 3 python beautifulsoup

我只想使用 BeautifulSoup 更改背景颜色样式:

我的 HTML :

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

我想做这样的事情:

soup_td = BeautifulSoup(html_td, "html.parser")
soup_td.td["style"]["background-color"] = "red;"
Run Code Online (Sandbox Code Playgroud)

Oma*_*nea 7

用于cssutils操作 CSS,如下所示:

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)
Run Code Online (Sandbox Code Playgroud)

如果您习惯使用正则表达式,也可以使用它。


IAs*_*dOS 7

这是上面一个相当复杂的答案;你也可以这样做:

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

将soup.findAll 与您想要使用的任何BeautifulSoup 选择器结合起来。

  • 这并不能回答问题,因为它覆盖了完整的“style”标签,而不是仅更改单个值。 (4认同)