Simon Lindgren
Simon Lindgren

Reputation: 2031

Extract title tag with BeautifulSoup

I have this:

date = chunk.find_all('a', title=True, class_='tweet-timestamp js-permalink     js-nav js-tooltip')

Which returns this:

<a class="tweet-timestamp js-permalink js-nav js-tooltip" href="/15colleen/status/537395294133313536" title="3:59 PM - 25 Nov 2014"><span class="_timestamp js-short-timestamp " data-aria-label-part="last" data-long-form="true" data-time="1416959997" data-time-ms="1416959997000">Nov 25</span></a>

Obviously get_text()returns Nov 25, but I want to extract the snippet 3:59 PM - 25 Nov 2014.

Upvotes: 6

Views: 21887

Answers (2)

Padraic Cunningham
Padraic Cunningham

Reputation: 180411

You just need .find and to extract ["title"]

from bs4 import BeautifulSoup

soup = BeautifulSoup(html)
print(soup.find("a",attrs={"class":"tweet-timestamp js-permalink js-nav js-tooltip"})["title"])

3:59 PM - 25 Nov 2014

Upvotes: 8

Avinash Raj
Avinash Raj

Reputation: 174706

Specify the list index along with the title index to get the value of title attribute.

>>> from bs4 import BeautifulSoup
>>> s = '<a class="tweet-timestamp js-permalink js-nav js-tooltip" href="/15colleen/status/537395294133313536" title="3:59 PM - 25 Nov 2014"><span class="_timestamp js-short-timestamp " data-aria-label-part="last" data-long-form="true" data-time="1416959997" data-time-ms="1416959997000">Nov 25</span></a>'
>>> soup = BeautifulSoup(s)
>>> date = soup.find_all('a', title=True, class_='tweet-timestamp js-permalink     js-nav js-tooltip')
>>> date
[<a class="tweet-timestamp js-permalink js-nav js-tooltip" href="/15colleen/status/537395294133313536" title="3:59 PM - 25 Nov 2014"><span class="_timestamp js-short-timestamp " data-aria-label-part="last" data-long-form="true" data-time="1416959997" data-time-ms="1416959997000">Nov 25</span></a>]
>>> date[0]['title']
'3:59 PM - 25 Nov 2014'

Upvotes: 5

Related Questions