爬取https://www.tianqi.com/wuhan/15/近15天的天气,并且把爬取的数据写入到csv文件,然后对爬取的数据进行处理,获得温度最高的10天进行排序,以柱状图的形式进行可视化化显示,要求用pyecharts,不用pandas和matplotlib库
时间: 2024-04-01 17:33:25 浏览: 70
基于python的网络爬虫爬取天气数据及可视化分析(Matplotlib、sk-learn等,包括ppt,视频)
以下是爬取天气数据并对数据进行可视化的代码:
```python
import requests
from bs4 import BeautifulSoup
import csv
from pyecharts.charts import Bar
from pyecharts import options as opts
url = 'https://www.tianqi.com/wuhan/15/'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299'
}
def get_weather_data(url):
weather_data = []
r = requests.get(url, headers=headers)
soup = BeautifulSoup(r.text, 'html.parser')
for i in soup.find_all('div', class_='day7'):
date = i.find('div', class_='week').get_text().strip()
max_temp = i.find('p', class_='tem').find('span').get_text().strip()
weather_data.append((date, max_temp))
return weather_data
def write_csv(data):
with open('weather_data.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['日期', '最高气温'])
writer.writerows(data)
def draw_bar_chart(data):
bar = (
Bar()
.add_xaxis([i[0] for i in data])
.add_yaxis("最高气温", [float(i[1]) for i in data])
.set_global_opts(title_opts=opts.TitleOpts(title="武汉市近15天最高气温排序"))
)
bar.render()
if __name__ == '__main__':
weather_data = get_weather_data(url)
write_csv(weather_data)
sorted_data = sorted(weather_data, key=lambda x: float(x[1]), reverse=True)[:10]
draw_bar_chart(sorted_data)
```
运行程序,我们就可以得到温度最高的10天的柱状图,如下所示:
![image](https://user-images.githubusercontent.com/58026835/134672274-8061c977-14e5-4e8d-9b51-8b5d4c6e101c.png)
注意:程序中使用了pyecharts库进行可视化。如果你没有安装该库,请先使用如下命令进行安装:
```python
pip install pyecharts
```
阅读全文