使用Beautiful Soup—;python

使用Beautiful Soup—;python,python,beautifulsoup,Python,Beautifulsoup,我想从下面的html中提取包含Beautiful Soup的文本“12:25 AM-2015年3月30日”。这是被BS处理后html的外观: <span class="u-floatLeft"> · </span> <span class="u-floatLeft"> <a class="ProfileTweet-timestamp js-permalink js-nav js-tooltip" href="/TBantl/status/58233363

我想从下面的html中提取包含Beautiful Soup的文本“12:25 AM-2015年3月30日”。这是被BS处理后html的外观:

<span class="u-floatLeft"> · </span>
<span class="u-floatLeft">
<a class="ProfileTweet-timestamp js-permalink js-nav js-tooltip" href="/TBantl/status/582333634931126272" title="5:08 PM - 29 Mar 2015">
<span class="js-short-timestamp " data-aria-label-part="last" data-long-form="true" data-time="1427674132">
Mar 29
  </span>
这对我很有用:

from bs4 import BeautifulSoup

html = """<span class="u-floatLeft">&nbsp;·&nbsp;</span>
          <span class="u-floatLeft">
          <a class="ProfileTweet-timestamp js-permalink js-nav js-tooltip" href="/indoz1/status/582443448927543296" title="12:25 AM - 30 Mar 2015">
          <span class="js-short-timestamp " data-aria-label-part="last" data-time="1427700314" data-long-form="true">
       """
soup = BeautifulSoup(html)
date = soup.find("a", attrs={"class": "ProfileTweet-timestamp js-permalink js-nav js-tooltip"})["title"]

>>> print(date)
'12:25 AM - 30 Mar 2015'

什么是块?另外,您确定所需的元素确实存在于正在解析的HTML中吗?请定义“它不工作”-您得到了什么输出?有什么错误吗?如果是这样的话,请回答你的问题并给出它们的全文。@MattDMo是的,这就是我决定提问的原因,代码看起来不错。最有可能的是,OP从浏览器复制了元素的HTML表示形式,而没有检查元素是否实际存在于由
BeautifulSoup
@alecxe
chunk
解析的HTML中。在这种情况下,chunk是
汤的名称。我已经编辑了这个问题,以显示漂亮的汤式html,其中包含元素。@textnet您的代码实际上看起来不错。尝试使用不同的解析器。e、 g.
chunk=BeautifulSoup(数据,'html.parser')
chunk=BeautifulSoup(数据,'lxml')
chunk=BeautifulSoup(数据,'html5lib')
。考虑到您所拥有的信息的缺乏,您真的做了所有可能的事情。非常努力!:)@MattDMo'date=chunk2.find(“a”,attrs={“class”:“js short timestamp”}[“data time”]')给了我`类型错误:'NoneType'对象没有属性'getitem'''@textnet
chunk2.find()
在本例中应该查找
“span”
,而不是
“a”
。改变这一点,你的代码就可以工作了。
from bs4 import BeautifulSoup

html = """<span class="u-floatLeft">&nbsp;·&nbsp;</span>
          <span class="u-floatLeft">
          <a class="ProfileTweet-timestamp js-permalink js-nav js-tooltip" href="/indoz1/status/582443448927543296" title="12:25 AM - 30 Mar 2015">
          <span class="js-short-timestamp " data-aria-label-part="last" data-time="1427700314" data-long-form="true">
       """
soup = BeautifulSoup(html)
date = soup.find("a", attrs={"class": "ProfileTweet-timestamp js-permalink js-nav js-tooltip"})["title"]

>>> print(date)
'12:25 AM - 30 Mar 2015'
from datetime import datetime as dt

# get "data-time" field value as string named timestamp
data_time = dt.fromtimestamp(int(timestamp))

>>> print(data_time)
datetime.datetime(2015, 3, 30, 3, 25, 14)