使用BeautifulSoup提取标题标记

时间:2015-03-05 10:37:48

标签: python beautifulsoup

我有这个:

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

返回此内容:

<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>

显然get_text()会返回Nov 25,但我想提取代码段3:59 PM - 25 Nov 2014

2 个答案:

答案 0 :(得分:5)

您只需要.find并提取["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

答案 1 :(得分:4)

指定列表索引以及标题索引以获取title属性的值。

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