【问题标题】:How to extract datetime from chunk of HTML如何从 HTML 块中提取日期时间
【发布时间】:2023-01-09 03:04:24
【问题描述】:

我有一段 HTML,其中包含这样的日期时间

<time datetime="2023-01-06 05:00:00" data-format="article-display" data-show-date="always" data-show-time="today-only" data-timestamp="1672981200" itemprop="datePublished" class="author-details__timestamp formatTimeStampEs6" full-date="05.01.2023">6th January</time>

我使用了 Chrome 检查器中的副本 JS,并将其返回

#article > div.mar-article > div > div.mar-article__timestamp > time

def extract_time(data):
    """Extract the time from the HTML of the article page."""
    soup = BeautifulSoup(data, 'html.parser')
    # Use the select_one() method to find the time element
    time_element = soup.find("time", class_="datetime")
    print(time_element)
    return time_element

为什么它返回无?

我很困惑,因为我不知道如何只返回日期时间。

【问题讨论】:

  • print(soup.find("time")) 显示什么?

标签: html google-chrome beautifulsoup


【解决方案1】:

该元素没有名为 datetime 的类,但您可以通过属性 datetime 选择它(前提是相应的元素也存在于汤中):

soup.select_one('time[datetime]').get('datetime')

例子

from bs4 import BeautifulSoup
soup = BeautifulSoup('<time datetime="2023-01-06 05:00:00" data-format="article-display" data-show-date="always" data-show-time="today-only" data-timestamp="1672981200" itemprop="datePublished" class="author-details__timestamp formatTimeStampEs6" full-date="05.01.2023">6th January</time>')

soup.select_one('time[datetime]').get('datetime')

输出

2023-01-06 05:00:00

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-23
    • 2019-05-08
    • 2019-01-23
    相关资源
    最近更新 更多