Fix Python – Get an attribute value based on the name attribute with BeautifulSoup

Question

Asked By – Ruth

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.

Now we will see solution for issue: Get an attribute value based on the name attribute with BeautifulSoup


Answer

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']
'Austin'

This question is answered By – theharshest

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0