dj1121 dj1121 - 3 years ago 54
HTML Question

Beautiful Soup find first <a> whose title attribute equal a certain string

I'm working with beautiful soup and am trying to grab the first tag on a page that has the attribute equal to a certain string.

For example:

<a href="url" title="export"></a>


What I've been trying to do is grab the href of the first that is found whose title is "export".


  • If I use
    soup.select("a[title='export']")
    then I end up finding all tags who satisfy this requirement, not just the first.

  • If I use
    find("a", {"title":"export"})
    with conditions being set such that the title should equal "export", then it grabs the actual items inside the tag, not the href.

  • If I write
    .get("href")
    after calling
    find()
    , I get None back.



I've been searching the documentation and stack overflow for an answer but have yet found one. Does anyone know a solution to this? Thank you!

Answer Source

What I've been trying to do is grab the href of the first that is found whose title is "export".

You're almost there. All you need to do is, once you've obtained the tag, you'll need to just index it to get the href. Here's a slightly more bulletproof version:

try:
    url = soup.find('a', {title : 'export' })['href']
    print(url)
except TypeError:
    pass
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download