Ruth Ruth - 8 months ago 49
Python Question

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

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.


It's pretty simple, use the following -

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

Leave a comment if anything is not clear.