写一个分类整理爬取数据的时间的代码
时间: 2024-06-09 20:09:22 浏览: 41
以下是一个示例代码,可以爬取网站上的数据并根据时间分类整理:
```python
import requests
from bs4 import BeautifulSoup
from datetime import datetime
# 爬取网站上的数据
url = 'https://www.example.com'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# 解析数据并分类整理
data = {}
for item in soup.find_all('div', {'class': 'item'}):
title = item.find('h2').text
time_str = item.find('span', {'class': 'time'}).text
time = datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
date_str = time.strftime('%Y-%m-%d')
if date_str not in data:
data[date_str] = []
data[date_str].append(title)
# 输出整理后的数据
for date in sorted(data.keys()):
print(date)
for title in data[date]:
print(f'- {title}')
```
在这个示例代码中,我们首先使用 requests 库获取网站的 HTML 内容,然后使用 BeautifulSoup 解析数据。我们假设每个数据项都包含一个标题和一个时间戳,并且时间戳的格式为 `%Y-%m-%d %H:%M:%S`。
在解析数据后,我们将数据按照日期分类整理,存储在一个字典中。最后,我们按照日期排序并输出整理后的数据。