Monkeypatching Beautiful Soup
Since html2css is built upon Beautiful Soup, it is relatively easy to monkeypatch it. (Especially since there is a shortcut in the code, that lets Soup objects be used directly, achieving greater speed.)
Monkeypatching BS to use html2css is as easy as this:
>>> from beautifulsoup import BeautifulSoup
>>> from html2css import html2css
>>> setattr(BeautifulSoup, 'toCss', lambda soup: html2css(soup).display())
>>> soup = BeautifulSoup('<html id="foo"><body></body></html>')
>>> print soup.toCss()
html {}
body {}
html#foo {}
html#foo body {}
There you go. (This also illustrates an advantage of Python’s explicit self
declaration, in that toCss
actually takes an argument (soup
), which is then used as a self
-declaration, meaning that toCss
can be called without arguments — otherwise, it would have been soup.toCss(soup)
, which really isn’t optimal.)