用python爬虫获取武汉市2023年5月份的温度数据并写入csv文件中并命名为武汉五月份温度.csv,再读取该csv文件中的温度数据生成可视化折线图,最后在HTML中展示
时间: 2024-04-02 13:32:45 浏览: 66
好的,我可以帮你完成这个任务。
首先,我们需要使用 Python 中的 requests 和 BeautifulSoup 库来爬取温度数据。代码如下:
```python
import requests
from bs4 import BeautifulSoup
import csv
# 请求 URL
url = 'http://www.tianqihoubao.com/lishi/wuhan/month/202305.html'
# 发送 GET 请求
html = requests.get(url).text
# 解析 HTML
soup = BeautifulSoup(html, 'html.parser')
# 获取表格
table = soup.find('table', {'class': 'b'})
# 获取表格中的所有行
rows = table.find_all('tr')
# 写入 CSV 文件
with open('武汉五月份温度.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
for row in rows:
# 获取每行的所有单元格
cells = row.find_all('td')
# 如果单元格数量大于 0,则写入 CSV 文件中
if len(cells) > 0:
date = cells[0].get_text().strip() # 日期
max_temp = cells[1].get_text().strip() # 最高温度
min_temp = cells[2].get_text().strip() # 最低温度
writer.writerow([date, max_temp, min_temp])
```
接下来,我们使用 Pandas 库来读取 CSV 文件,并使用 Matplotlib 库生成折线图。代码如下:
```python
import pandas as pd
import matplotlib.pyplot as plt
# 读取 CSV 文件
df = pd.read_csv('武汉五月份温度.csv', header=None, names=['日期', '最高温度', '最低温度'])
# 生成折线图
plt.plot(df['日期'], df['最高温度'], label='最高温度')
plt.plot(df['日期'], df['最低温度'], label='最低温度')
plt.xlabel('日期')
plt.ylabel('温度')
plt.title('武汉五月份温度')
plt.legend()
# 在 HTML 中展示
from IPython.core.display import HTML
HTML('<img src="data:image/png;base64,{}"/>'.format(
df.plot().get_figure().savefig('plot.png', bbox_inches='tight', pad_inches=0.1, format='png', dpi=300, transparent=False)
))
```
最后,我们可以在 Jupyter Notebook 或 IPython 中运行上述代码,就可以看到生成的折线图,并在 HTML 中展示。
阅读全文
相关推荐









