英文:
How to extract datetime from chunk of HTML
问题
返回的翻译部分如下:
为什么它返回None?
我感到困惑,因为我不知道如何仅返回日期时间。
英文:
I have a piece of HTML that includes a datetime like this
<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>
I've used the copy JS from Chrome inspector and had this returned
#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
Why does it return None?
I'm confused as I don't know how to return just the datetime.
答案1
得分: 1
这个元素没有名为 datetime
的 class,但您可以通过其 attribute 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
英文:
The element do not have a class called datetime
but you could select it by its attribute datetime
(provided that the corresponding element is also present in the soup):
soup.select_one('time[datetime]').get('datetime')
Example
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')
Output
2023-01-06 05:00:00
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论