Hi Emilio,
apologies for the delay. Your reply gave me enough pointers to get this to work (with the help of ChatGPT!).
An abridged version of the code is below:
import cssutils # type: ignore[import-untyped]
import pandas as pd
from bs4 import BeautifulSoup
from pandas.io.formats.style import Styler
class StyleData
def style_area_data_for_seeq_topic(
self,
area: str,
data_df: pd.DataFrame,
*,
reverse_sort: bool = False,
) -> str:
"""Style the data for the Seeq topic."""
styler = self._style_area_data(
area,
data_df,
reverse_sort=reverse_sort,
)
if styler is None:
msg = f"Styler for {area} is None."
raise ValueError(msg)
soup = BeautifulSoup(styler.to_html(), "html.parser")
style_tag = soup.find("style")
if style_tag is None:
msg = f"Style tag for {area} is None."
raise ValueError(msg)
parser = cssutils.CSSParser()
stylesheet = parser.parseString(getattr(style_tag, "string", None))
for rule in stylesheet:
if rule.type == rule.STYLE_RULE:
selector = rule.selectorText
style = rule.style.cssText
elements = soup.select(selector)
for el in elements:
existing_style = el.get("style", "")
new_style = existing_style + style
el["style"] = new_style
style_tag.extract()
return str(soup.prettify().strip())