home ~ projects ~ socials

Python Beautiful Soup Example

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)
Output:
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.

-- end of line --