这篇文章主要介绍了python爬取数据保存到数据库,具有一定借鉴价值,需要的朋友可以参考下。希望大家阅读完这篇文章后大有收获,下面让小编带着大家一起了解一下。
Source code download: 本文相关源码
通过爬虫爬取天气数据,进行数据处理,最后可视化呈现
具体步骤:
1.指定url网址
在这里爬取的目标是www.tianqi.com网站里面武汉的2022历史天气
查看页面源代码,发现所需要的信息再thrui中的li标签下
指定url网址,这里爬取2022全年的天气数据
for month in range(1,13): #获取某一月的天气信息,三元表达式
weather_time = '2022'+ ('0'+str(month)if month < 10 else str(month))
print(weather_time)
url = f'https://lishi.tianqi.com/wuhan/{weather_time}.html'
weather = getWeather(url) #爬取当前页面数据
weathers.append(weather) #存到列表中
print(weathers)
2.发送请求,访问网址
3.获取响应数据
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0'
}
response = requests.get(url,headers=headers)
#预处理数据
response_html = etree.HTML(response.text)
#xpath提取所有的数据
response_list = response_html.xpath("//ul[@class='thrui']/li")
4.持久化存储,保存在数据库或本地
#写入数据
with open("weather.csv","w",newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['日期','最高气温','最低气温','天气']) #写入列名
#用writerows一次写入多行
writer.writerows([list(day_weather_dict.values()) for month_weather in weathers for day_weather_dict in month_weather])
完整代码
import requests
from lxml import etree
import csv
def getWeather(url): #新建一个列表,将爬取的每月数据放入
weather_info = []
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0'
}
response = requests.get(url,headers=headers)
#预处理数据
response_html = etree.HTML(response.text)
#xpath提取所有的数据
response_list = response_html.xpath("//ul[@class='thrui']/li")
for li in response_list:
day_weather_info = {}
day_weather_info['date_time'] = li.xpath("./div[1]/text()")[0].split(' ')[0]
#最高温度
high = li.xpath("./div[2]/text()")[0]
day_weather_info['high'] = high[:high.find('℃')]
low = li.xpath("./div[3]/text()")[0]
day_weather_info['low'] = low[:low.find('℃')]
#天气
day_weather_info['weather'] = li.xpath("./div[4]/text()")[0]
weather_info.append(day_weather_info)
return weather_info
weathers = []
#for 循环生成有顺序的1-12
for month in range(1,13): #获取某一月的天气信息,三元表达式
weather_time = '2022'+ ('0'+str(month)if month < 10 else str(month))
print(weather_time)
url = f'https://lishi.tianqi.com/wuhan/{weather_time}.html'
weather = getWeather(url) #爬取当前页面数据
weathers.append(weather) #存到列表中
print(weathers)
#写入数据
with open("weather.csv","w",newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['日期','最高气温','最低气温','天气']) #写入列名
#用writerows一次写入多行
writer.writerows([list(day_weather_dict.values()) for month_weather in weathers for day_weather_dict in month_weather])
最后将爬取到的结过保存为csv文件,文件名为weather.csv
接下来进行可视化呈现
完整代码
import pandas as pd
from pyecharts import options as opts
from pyecharts.charts import Pie ,Bar,Timeline
#用pandas.read_csv()读取指点的excel文件
df = pd.read_csv('weather.csv',encoding = 'gb18030')
print(df['日期'])
df['日期'] = df ['日期'].apply(lambda x: pd.to_datetime(x))
print(df['日期'])
#新建一个月份数据,实际是将日期中的月份一项拿出来
df['month'] = df['日期'].dt.month
#需要的数据,每个月中每种天气的出现次数
print(df['month'])
df_agg = df.groupby(['month','天气']).size().reset_index() #返回dataframe groupby聚合对象,分组和统计的, size()能计算分组的大小
print(df_agg)
df_agg.columns = ['month','tianqi','count']
#天气数据的形成 values numpy 数组 tolist 列表数据
print(df_agg[df_agg['month']==1][['tianqi','count']]\
.sort_values(by='count',ascending=False).values.tolist())
#画图 实例化一个时间序列的对象
timeline = Timeline()
timeline.add_schema(play_interval=1000) #设置播放时间间隔为1s
#循环便利df_agg中['month']的唯一值
for month in df_agg['month'].unique():
data = (
df_agg[df_agg['month']==month][['tianqi','count']]
.sort_values(by='count',ascending=True)
.values.tolist()
)
#答应出时间,绘制柱状图
bar =Bar() #x轴是天气的名称,y轴是出现次数
bar.add_xaxis([x[0] for x in data])
bar.add_yaxis('',[x[1] for x in data])
#可视化图形样式设置
bar.reversal_axis() #柱状图转向
bar.set_series_opts(label_opts=opts.LabelOpts(position='right'))
bar.set_global_opts(title_opts=opts.TitleOpts(title='武汉2022年度每月天气的变化'))
timeline.add(bar,f'{month}月')
timeline.render('weathers1.html')
最后在当前文件夹生成weathers1.html文件,打开即可