Python Forum

Full Version: Using beautiful soup to get html attribute value
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi Guys,

What i'm trying to do is use beautiful soup to get the value of an html attribute.

<div class="g-recaptcha" data-sitekey="VALUE_TO_RETURN"></div>

What i have so far is:

soup = BeautifulSoup(html, "html.parser")
print("data-sitekey=" + soup.find("div", {"class" : "data-sitekey"}))
return soup.find("div", {"class" : "data-sitekey"})
But this returns "must be str, not nulltype"

any help would be appreciated.

cheers guys
from bs4 import BeautifulSoup

html = '''\
<div class="g-recaptcha" data-sitekey="VALUE_TO_RETURN"></div>'''

soup = BeautifulSoup(html, 'lxml')
>>> tag = soup.find('div', class_="g-recaptcha")
>>> tag
<div class="g-recaptcha" data-sitekey="VALUE_TO_RETURN"></div>

>>> tag.attrs
{'class': ['g-recaptcha'], 'data-sitekey': 'VALUE_TO_RETURN'}
>>> tag.attrs.get('data-sitekey')
'VALUE_TO_RETURN'
Thank you very much Snippsat :)