python获取天气分析_Python爬取南京市往年天气预报,使用pyecharts进行分析
时间: 2024-03-29 09:35:57 浏览: 16
获取南京市往年天气预报可以通过爬取相关网站的数据来实现。我推荐使用Python中的requests和BeautifulSoup库来实现数据爬取和解析。以下是示例代码:
```python
import requests
from bs4 import BeautifulSoup
year = 2020 # 爬取的年份
url = f'http://www.tianqihoubao.com/lishi/nanjing/month/{year}{str(1).zfill(2)}.html' # 目标网站URL
# 发送请求获取HTML文本
response = requests.get(url)
html = response.content.decode('gbk')
# 解析HTML文本获取天气数据
soup = BeautifulSoup(html, 'html.parser')
table = soup.find('table', attrs={'class': 'b'})
rows = table.find_all('tr')[1:] # 第一行为表头,去掉
for row in rows:
data = row.find_all('td')
date = data[0].text.replace('\n', '') # 日期
high = data[1].text.replace('\n', '') # 最高气温
low = data[2].text.replace('\n', '') # 最低气温
weather = data[3].text.replace('\n', '') # 天气
wind_direction = data[4].text.replace('\n', '') # 风向
wind_power = data[5].text.replace('\n', '') # 风力
print(date, high, low, weather, wind_direction, wind_power)
```
获取到天气数据后,可以使用pyecharts进行数据可视化分析。以下是示例代码:
```python
from pyecharts.charts import Line
from pyecharts import options as opts
# 处理数据
x_data = [f'{year}-{str(i).zfill(2)}' for i in range(1, 13)] # x轴数据
y_data_high = [] # 最高气温数据
y_data_low = [] # 最低气温数据
for month in range(1, 13):
url = f'http://www.tianqihoubao.com/lishi/nanjing/month/{year}{str(month).zfill(2)}.html'
response = requests.get(url)
html = response.content.decode('gbk')
soup = BeautifulSoup(html, 'html.parser')
table = soup.find('table', attrs={'class': 'b'})
rows = table.find_all('tr')[1:]
high_temps = [int(row.find_all('td')[1].text) for row in rows]
low_temps = [int(row.find_all('td')[2].text) for row in rows]
y_data_high.append(sum(high_temps) / len(high_temps))
y_data_low.append(sum(low_temps) / len(low_temps))
# 绘制折线图
line = Line()
line.add_xaxis(x_data)
line.add_yaxis('最高气温', y_data_high)
line.add_yaxis('最低气温', y_data_low)
line.set_global_opts(title_opts=opts.TitleOpts(title='南京市{}年气温变化'.format(year)))
line.render('nanjing_temp.html')
```
以上代码会生成一个HTML文件,可以在浏览器中打开查看绘制好的折线图。