Python: BeautifulSoup - get an attribute value based on the name attribute

Ruth picture Ruth · Jun 26, 2012 · Viewed 153.2k times · Source

I want to print an attribute value based on its name, take for example

<META NAME="City" content="Austin">

I want to do something like this

soup = BeautifulSoup(f) //f is some HTML containing the above meta tag
for meta_tag in soup('meta'):
    if meta_tag['name'] == 'City':
         print meta_tag['content']

The above code give a KeyError: 'name', I believe this is because name is used by BeatifulSoup so it can't be used as a keyword argument.

Answer

theharshest picture theharshest · Jun 26, 2012

It's pretty simple, use the following -

>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup('<META NAME="City" content="Austin">')
>>> soup.find("meta", {"name":"City"})
<meta name="City" content="Austin" />
>>> soup.find("meta", {"name":"City"})['content']
u'Austin'

Leave a comment if anything is not clear.