Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Python Beautiful Soup Example

Code

from bs4 import BeautifulSoup

html = """
<html>
  <div class="target" style="color: #123434">Content</div>
</html>
"""

soup = BeautifulSoup(html, 'html.parser')
divs = soup.find_all('div', 'target')
div = divs[0]
style = div.attrs['style']

print(style)

Results

color: #123434

NOTE: The docs say you can use this:

style = div.attrs['style']

instead of this:

style = div['style']

but that doesn't work consistently for me.

I think that was because I was trying to do:

#+begin_example if 'thing' in element: print('here') #+end_example

and the `in` check doesn't work there. So, I'm just using `.attrs` all the time for consistency.