用python第三方库Requests,BeautifulSoup,NumPy,pandas,Matplotlib 写一个天气预报统计的代码
时间: 2024-03-30 11:34:35 浏览: 17
好的,下面是一个简单的使用Requests,BeautifulSoup,NumPy,pandas和Matplotlib的天气预报统计代码示例:
```python
import requests
from bs4 import BeautifulSoup
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# 获取天气预报页面的HTML
url = 'https://www.tianqi.com/beijing/'
response = requests.get(url)
html = response.content.decode('utf-8')
# 使用BeautifulSoup解析HTML
soup = BeautifulSoup(html, 'html.parser')
# 获取天气预报数据
weather_list = []
for ul in soup.find_all('ul', class_='week'):
for li in ul.find_all('li'):
day = li.find('h1').text
weather = li.find('span', class_='wea').text
temp = li.find('div', class_='tem').text
weather_list.append([day, weather, temp])
# 将天气预报数据转换为DataFrame
df = pd.DataFrame(weather_list, columns=['Day', 'Weather', 'Temperature'])
# 统计天气数据
weather_counts = df['Weather'].value_counts()
# 绘制天气数据图表
fig, ax = plt.subplots()
ax.bar(weather_counts.index, weather_counts.values)
ax.set_title('Weather Forecast')
ax.set_xlabel('Weather')
ax.set_ylabel('Count')
plt.show()
```
这个代码会从天气网站上获取北京的天气预报数据,并将其转换为DataFrame,然后统计不同天气情况的出现次数,并用Matplotlib绘制柱状图展示。