How to find tags with only certain attributes – BeautifulSoup

As explained on the BeautifulSoup documentation

You may use this :

soup = BeautifulSoup(html)
results = soup.findAll("td", {"valign" : "top"})

EDIT :

To return tags that have only the valign=”top” attribute, you can check for the length of the tag attrs property :

from BeautifulSoup import BeautifulSoup

html="<td valign="top">.....</td>\
        <td width="580" valign="top">.......</td>\
        <td>.....</td>"

soup = BeautifulSoup(html)
results = soup.findAll("td", {"valign" : "top"})

for result in results :
    if len(result.attrs) == 1 :
        print result

That returns :

<td valign="top">.....</td>

Leave a Comment