主题式网络爬虫名称——爬取中国天气网数据
主题式网络爬虫名称——爬取中国天气网数据
选题背景
一天的天气变化影响着方方面面,农业上,对天气进行预测可以用来安排相应地工作和生活,特别是灾害性的天气预报,保护着人们的生命财产,促进经济发展等方面发挥着重要作用。而python主题式网络爬虫能尽可能多的发现和搜集与预定主题相关的网页,具备分析网页内容和判别主题相关度的能力,通过对中国天气网的爬取,获取天气变化数据数据。
主题式网络爬虫设计方案
(1)主题式网络爬虫名称——爬取中国天气网数据
(2)主题式网络爬虫爬取的内容
利用python爬取中国天气网某个城市的一周时间内的天气变化,最低温,最高温以及风级。
(3)数据特征分析
利用python自带的多个第三方库pandas、numpy和requests爬取库、beautiful soup库对数据进行统计和分析,比较某两个关系之间的特征联系。
(4)方案概述
获取网页请求
解析获取的网页
提取数据
保存文件
数据清洗
统计数据
HTML页面解析
爬取的url为http://www.weather.com.cn
网址首页如下,进入页面后点击鼠标右键,在选项中利用浏览器的审查功能,获取页面的元素和源代码,也可以通过点击页面中某些关键信息,查看所需字段所在标签位置。
从网页源代码可以看出,我们所需要的字段全部在id=“7d”中的div中的ul中 ,<ul> 标签定义无序列表。
日期在标签li中的h1标签中,天气情况在第一个p标签中。
最高温度在第二个p标签的span 标签中,最低温度在第二个p标签的 i 标签中。
风级在第三个p标签中的 i 标签中。其结构如图所示。
节点查找与遍历方法
爬取网页
import requests from bs4 import BeautifulSoup import csv import json def getHTMLtext(url): """请求获得网页内容""" try: r = requests.get(url, timeout = 30) r.raise_for_status() r.encoding = r.apparent_encoding print("成功访问") return r.text except: print("访问错误") return" " def get_content(html): """处理得到有用信息保存数据文件""" list= [] #初始化创建列表保存数据 bs = BeautifulSoup(html, "html.parser") #创建beautiful soup爬取对象 body = bs.body data = body.find('div', {'id': '7d'}) #找到div标签且id=7d #爬取当天数据 data2 = body.find_all('div',{'class':'left-div'}) text = data2[2].find('script').string text = text[text.index('=')+1 :-2] #移除该var data=将其变为json数据 jd = json.loads(text) dayone = jd['od']['od2'] #找到当天数据 list_day = [] #存放当天数据 count = 0 for i in dayone: temp = [] if count <=23: temp.append(i['od21']) #添加时间 temp.append(i['od22']) #添加当前时刻温度 temp.append(i['od24']) #添加当前时刻风力方向 temp.append(i['od25']) #添加当前时刻风力等级 temp.append(i['od26']) #添加当前时刻降水量 temp.append(i['od27']) #添加当前时刻相对湿度 temp.append(i['od28']) #添加当前时刻控制质量 #print(temp) list_day.append(temp) count = count +1 #爬取七天数据 ul = data.find('ul') #找到所有ul标签 li = ul.find_all('li') #找到左右的li标签 i = 0 #控制天数 for day in li: #遍历找到每个li if i < 7 and i > 0: temp = [] #临时存放每天数据 date = day.find('h1').string #得到日期 date = date[0:date.index('日')] #取出日期号 temp.append(date) inf = day.find_all('p') #找出li下面的p标签,提取第一个p标签的值 temp.append(inf[0].string) tem_low = inf[1].find('i').string #找到最低气温 if inf[1].find('span') is None: #天气预报可能没有最高气温 tem_high = None else: tem_high = inf[1].find('span').string #找到最高气温 temp.append(tem_low[:-1]) if tem_high[-1] == '℃': temp.append(tem_high[:-1]) else: temp.append(tem_high) wind = inf[2].find_all('span') #找到风向 for j in wind: temp.append(j['title']) wind_scale = inf[2].find('i').string #找到风级 index1 = wind_scale.index('级') temp.append(int(wind_scale[index1-1:index1])) list.append(temp) i = i + 1 return list_day,final #print(final) def get_content2(html): """处理得到有用信息保存数据文件""" list = [] #初始化一个列表保存数据 bs = BeautifulSoup(html, "html.parser") #创建beautiful soup对象 body = bs.body data = body.find('div', {'id': '15d'}) #找到div标签且id=15d ul = data.find('ul') #找到所有ul标签 li = ul.find_all('li') #找到左右的li标签 list = [] i = 0 #控制天数 for day in li: #遍历找到每个li if i < 8: temp = [] #临时存放数据 date = day.find('span',{'class':'time'}).string #得到日期 date = date[date.index('(')+1:-2] #取出日期 temp.append(date) weather = day.find('span',{'class':'wea'}).string #找到天气 temp.append(weather) tem = day.find('span',{'class':'tem'}).text #找到温度 temp.append(tem[tem.index('/')+1:-1]) #找到最低气温 temp.append(tem[:tem.index('/')-1]) #找到最高气温 wind = day.find('span',{'class':'wind'}).string #找到风向 if '转' in wind: #如果有风向变化 temp.append(wind[:wind.index('转')]) temp.append(wind[wind.index('转')+1:]) else: #若没有风向变化,前后一致 temp.append(wind) temp.append(wind) wind_scale = day.find('span',{'class':'wind1'}).string #找到风级 index1 = wind_scale.index('级') temp.append(int(wind_scale[index1-1:index1])) list.append(temp) return list
运行结果如下
保存数据
def write_to_csv(file_name, data, day=14): """保存为csv文件""" with open(file_name, 'a', errors='ignore', newline='') as f: if day == 14: header = ['日期','天气','最低气温','最高气温','风向1','风向2','风级'] else: header = ['小时','温度','风力方向','风级','降水量','相对湿度','空气质量'] f_csv = csv.writer(f) f_csv.writerow(header) f_csv.writerows(data) def main(): """主函数""" print("Weather test") url1 = 'http://www.weather.com.cn/weather/101280701.shtml' #7天天气中国天气网 url2 = 'http://www.weather.com.cn/weather15d/101280701.shtml' #8-15天天气中国天气网 html1 = getHTMLtext(url1) data1, data1_7 = get_content(html1) #获得1-7天和当天的数据 html2 = getHTMLtext(url2) data8_14 = get_content2(html2) #获得8-14天的数据 data14 = data1_7 + data8_14 #print(data) write_to_csv('weather14.csv',data14,14) #保存为csv文件 write_to_csv('weather1.csv',data1,1) if __name__ == '__main__': main()
文件结果如下
数据清理和可视化
1、一天湿度变化数据可视化图
import matplotlib.pyplot as plt import numpy as np import pandas as pd import math data = pd.read_csv('weather1.csv',encoding='gb2312') """相对湿度曲线绘制""" hour = list(data['小时']) hum = list(data['相对湿度']) for i in range(0,24): if math.isnan(hum[i]) == True: hum[i] = hum[i-1] hum_ave = sum(hum)/24 # 求平均相对湿度 hum_max = max(hum) hum_max_hour = hour[hum.index(hum_max)] # 求最高相对湿度 hum_min = min(hum) hum_min_hour = hour[hum.index(hum_min)] # 求最低相对湿度 x = [] y = [] for i in range(0, 24): x.append(i) y.append(hum[hour.index(i)]) plt.figure(2) plt.plot(x,y,color='green',label='相对湿度') plt.scatter(x,y,color='green') # 点出每个时刻的相对湿度 plt.plot([0, 24], [hum_ave, hum_ave], c='red', linestyle='--',label='平均相对湿度') plt.text(hum_max_hour+0.2, hum_max+0.2, str(hum_max), ha='center', va='bottom', fontsize=10.5) plt.text(hum_min_hour+0.2, hum_min+0.2, str(hum_min), ha='center', va='bottom', fontsize=10.5) plt.xticks(x) plt.legend() plt.title('一天相对湿度变化曲线图') plt.xlabel('时间/h') plt.ylabel('百分比/%') plt.show()
结果如下
2、一天的温度变化数据可视化图
import matplotlib.pyplot as plt import numpy as np import pandas as pd import math data = pd.read_csv('weather1.csv',encoding='gb2312') """温度曲线绘制""" hour = list(data['小时']) tem = list(data['温度']) for i in range(0,24): if math.isnan(tem[i]) == True: tem[i] = tem[i-1] tem_ave = sum(tem)/24 # 求平均温度 tem_max = max(tem) tem_max_hour = hour[tem.index(tem_max)] # 求最高温度 tem_min = min(tem) tem_min_hour = hour[tem.index(tem_min)] # 求最低温度 x = [] y = [] for i in range(0, 24): x.append(i) y.append(tem[hour.index(i)]) plt.figure(1) plt.plot(x,y,color='green',label='温度') # 画出温度曲线 plt.scatter(x,y,color='green') # 点出每个时刻的温度点 plt.plot([0, 24], [tem_ave, tem_ave], c='red', linestyle='--',label='平均温度') # 画出平均温度虚线 plt.text(tem_max_hour+0.2, tem_max+0.2, str(tem_max), ha='center', va='bottom', fontsize=10.5) # 标出最高温度 plt.text(tem_min_hour+0.2, tem_min+0.2, str(tem_min), ha='center', va='bottom', fontsize=10.5) # 标出最低温度 plt.xticks(x) plt.legend() plt.title('一天温度变化曲线图') plt.xlabel('时间/h') plt.ylabel('摄氏度/℃') plt.show()
运行结果如下
3、一天的空气质量数据可视化图
import matplotlib.pyplot as plt import numpy as np import pandas as pd import math data = pd.read_csv('weather1.csv',encoding='gb2312') hour = list(data['小时']) air = list(data['空气质量']) print(type(air[0])) for i in range(0,24): if math.isnan(air[i]) == True: air[i] = air[i-1] air_ave = sum(air)/24 # 求平均空气质量 air_max = max(air) air_max_hour = hour[air.index(air_max)] # 求最高空气质量 air_min = min(air) air_min_hour = hour[air.index(air_min)] # 求最低空气质量 x = [] y = [] for i in range(0, 24): x.append(i) y.append(air[hour.index(i)]) plt.figure(3) for i in range(0,24): if y[i] <= 50: plt.bar(x[i],y[i],color='lightblue',width=0.9) # 1等级 elif y[i] <= 100: plt.bar(x[i],y[i],color='wheat',width=0.9) # 2等级 elif y[i] <= 150: plt.bar(x[i],y[i],color='red',width=0.9) # 3等级 elif y[i] <= 200: plt.bar(x[i],y[i],color='greenred',width=0.9) # 4等级 elif y[i] <= 300: plt.bar(x[i],y[i],color='darkviolet',width=0.9) # 5等级 elif y[i] > 300: plt.bar(x[i],y[i],color='maroon',width=0.9) # 6等级 plt.plot([0, 24], [air_ave, air_ave], c='black', linestyle='--') plt.text(air_max_hour+0.2, air_max+0.2, str(air_max), ha='center', va='bottom', fontsize=10.5) plt.text(air_min_hour+0.2, air_min+0.2, str(air_min), ha='center', va='bottom', fontsize=10.5) plt.title('一天空气质量变化曲线图') plt.xlabel('时间/h') plt.ylabel('空气质量指数AQI') plt.show()
运行结果如下
4、风力雷达图
import matplotlib.pyplot as plt import numpy as np import pandas as pd import mathdef wind_radar(data): """风向雷达图""" wind = list(data['风力方向']) wind_speed = list(data['风级']) for i in range(0,24): if wind[i] == "北风": wind[i] = 90 elif wind[i] == "南风": wind[i] = 270 elif wind[i] == "西风": wind[i] = 180 elif wind[i] == "东风": wind[i] = 360 elif wind[i] == "东北风": wind[i] = 45 elif wind[i] == "西北风": wind[i] = 135 elif wind[i] == "西南风": wind[i] = 225 elif wind[i] == "东南风": wind[i] = 315 degs = np.arange(45,361,45) temp = [] for deg in degs: speed = [] # 获取 wind_deg 在指定范围的风速平均值数据 for i in range(0,24): if wind[i] == deg: speed.append(wind_speed[i]) if len(speed) == 0: temp.append(0) else: temp.append(sum(speed)/len(speed)) print(temp) N = 8 theta = np.arange(0.+np.pi/8,2*np.pi+np.pi/8,2*np.pi/8) # 数据极径 radii = np.array(temp) # 绘制极区图坐标系 plt.axes(polar=True) # 定义每个扇区的RGB值(R,G,B),x越大,对应的颜色越接近蓝色 colors = [(1-x/max(temp), 1-x/max(temp),0.6) for x in radii] plt.bar(theta,radii,width=(2*np.pi/N),bottom=0.0,color=colors) plt.title('一天风级图',x=0.2,fontsize=20) plt.show() wind_radar(data)
运行结果如下
14天的气温相关性分析图
import numpy as np import pandas as pd import math import matplotlib.pyplot as plt data = pd.read_csv('weather14.csv',encoding='gb2312') day = data['日期'] tem = data['最高气温'] plt.scatter(day, tem, color='green') plt.title("温度相关性分析图") plt.xlabel("日期") plt.ylabel("温度/℃") plt.text(9, 20, "相关系数为:" + str(calc_corr(day, tem)), fontdict={'size': '10', 'color': 'red'}) plt.show()
运行结果如下
完整代码如下
import requests from bs4 import BeautifulSoup import csv import json def getHTMLtext(url): """请求获得网页内容""" try: r = requests.get(url, timeout = 30) r.raise_for_status() r.encoding = r.apparent_encoding print("成功访问") return r.text except: print("访问错误") return" " def get_content(html): """处理得到有用信息保存数据文件""" list = [] # 初始化一个列表保存数据 bs = BeautifulSoup(html, "html.parser") # 创建BeautifulSoup对象 body = bs.body data = body.find('div', {'id': '7d'}) # 找到div标签且id = 7d # 下面爬取当天的数据 data2 = body.find_all('div',{'class':'left-div'}) text = data2[2].find('script').string text = text[text.index('=')+1 :-2] # 移除改var data=将其变为json数据 jd = json.loads(text) dayone = jd['od']['od2'] # 找到当天的数据 final_day = [] # 存放当天的数据 count = 0 for i in dayone: temp = [] if count <=23: temp.append(i['od21']) # 添加时间 temp.append(i['od22']) # 添加当前时刻温度 temp.append(i['od24']) # 添加当前时刻风力方向 temp.append(i['od25']) # 添加当前时刻风级 temp.append(i['od26']) # 添加当前时刻降水量 temp.append(i['od27']) # 添加当前时刻相对湿度 temp.append(i['od28']) # 添加当前时刻控制质量 #print(temp) final_day.append(temp) count = count +1 # 下面爬取7天的数据 ul = data.find('ul') li = ul.find_all('li') i = 0 # 控制爬取的天数 for day in li: # 遍历找到的每一个li if i < 7 and i > 0: temp = [] # 临时存放每天的数据 date = day.find('h1').string # 得到日期 date = date[0:date.index('日')] # 取出日期号 temp.append(date) inf = day.find_all('p') # 找出li下面的p标签,提取第一个p标签的值,即天气 temp.append(inf[0].string) tem_low = inf[1].find('i').string # 找到最低气温 if inf[1].find('span') is None: # 天气预报可能没有最高气温 tem_high = None else: tem_high = inf[1].find('span').string temp.append(tem_low[:-1]) if tem_high[-1] == '℃': temp.append(tem_high[:-1]) else: temp.append(tem_high) wind = inf[2].find_all('span') # 找到风向 for j in wind: temp.append(j['title']) wind_scale = inf[2].find('i').string # 找到风级 index1 = wind_scale.index('级') temp.append(int(wind_scale[index1-1:index1])) list.append(temp) i = i + 1 return list_day,final #print(list) def get_content2(html): """处理得到有用信息保存数据文件""" list = [] bs = BeautifulSoup(html, "html.parser") # 创建BeautifulSoup对象 body = bs.body data = body.find('div', {'id': '15d'}) # 找到div标签且id = 15d ul = data.find('ul') # 找到所有的ul标签 li = ul.find_all('li') # 找到左右的li标签 list = [] i = 0 # 控制爬取的天数 for day in li: # 遍历找到的每一个li if i < 8: temp = [] # 临时存放每天的数据 date = day.find('span',{'class':'time'}).string date = date[date.index('(')+1:-2] temp.append(date) weather = day.find('span',{'class':'wea'}).string temp.append(weather) tem = day.find('span',{'class':'tem'}).text temp.append(tem[tem.index('/')+1:-1]) temp.append(tem[:tem.index('/')-1]) wind = day.find('span',{'class':'wind'}).string if '转' in wind: temp.append(wind[:wind.index('转')]) temp.append(wind[wind.index('转')+1:]) else: # 如果没有风向变化,前后风向一致 temp.append(wind) temp.append(wind) wind_scale = day.find('span',{'class':'wind1'}).string # 找到风级 index1 = wind_scale.index('级') temp.append(int(wind_scale[index1-1:index1])) list.append(temp) return list def write_to_csv(file_name, data, day=14): """保存为csv文件""" with open(file_name, 'a', errors='ignore', newline='') as f: if day == 14: header = ['日期','天气','最低气温','最高气温','风向1','风向2','风级'] else: header = ['小时','温度','风力方向','风级','降水量','相对湿度','空气质量'] f_csv = csv.writer(f) f_csv.writerow(header) f_csv.writerows(data) def main(): """主函数""" print("Weather test") url1 = 'http://www.weather.com.cn/weather/101280701.shtml' # 7天天气中国天气网 url2 = 'http://www.weather.com.cn/weather15d/101280701.shtml' # 8-15天天气中国天气网 html1 = getHTMLtext(url1) data1, data1_7 = get_content(html1) # 获得1-7天和当天的数据 html2 = getHTMLtext(url2) data8_14 = get_content2(html2) # 获得8-14天数据 data14 = data1_7 + data8_14 #print(data) write_to_csv('weather14.csv',data14,14) # 保存为csv文件 write_to_csv('weather1.csv',data1,1) if __name__ == '__main__': main() import matplotlib.pyplot as plt import numpy as np import pandas as pd import math data = pd.read_csv('weather1.csv',encoding='gb2312') """温度曲线绘制""" hour = list(data['小时']) tem = list(data['温度']) for i in range(0,24): if math.isnan(tem[i]) == True: tem[i] = tem[i-1] tem_ave = sum(tem)/24 # 求平均温度 tem_max = max(tem) tem_max_hour = hour[tem.index(tem_max)] # 求最高温度 tem_min = min(tem) tem_min_hour = hour[tem.index(tem_min)] # 求最低温度 x = [] y = [] for i in range(0, 24): x.append(i) y.append(tem[hour.index(i)]) plt.figure(1) plt.plot(x,y,color='green',label='温度') # 画出温度曲线 plt.scatter(x,y,color='green') # 点出每个时刻的温度点 plt.plot([0, 24], [tem_ave, tem_ave], c='red', linestyle='--',label='平均温度') # 画出平均温度虚线 plt.text(tem_max_hour+0.2, tem_max+0.2, str(tem_max), ha='center', va='bottom', fontsize=10.5) # 标出最高温度 plt.text(tem_min_hour+0.2, tem_min+0.2, str(tem_min), ha='center', va='bottom', fontsize=10.5) # 标出最低温度 plt.xticks(x) plt.legend() plt.title('一天温度变化曲线图') plt.xlabel('时间/h') plt.ylabel('摄氏度/℃') plt.show() hum = list(data['相对湿度']) for i in range(0,24): if math.isnan(hum[i]) == True: hum[i] = hum[i-1] hum_ave = sum(hum)/24 # 求平均相对湿度 hum_max = max(hum) hum_max_hour = hour[hum.index(hum_max)] # 求最高相对湿度 hum_min = min(hum) hum_min_hour = hour[hum.index(hum_min)] # 求最低相对湿度 x = [] y = [] for i in range(0, 24): x.append(i) y.append(hum[hour.index(i)]) plt.figure(2) plt.plot(x,y,color='green',label='相对湿度') # 画出相对湿度曲线 plt.scatter(x,y,color='green') # 点出每个时刻的相对湿度 plt.plot([0, 24], [hum_ave, hum_ave], c='red', linestyle='--',label='平均相对湿度') # 画出平均相对湿度虚线 plt.text(hum_max_hour+0.15, hum_max+0.15, str(hum_max), ha='center', va='bottom', fontsize=10.5) # 标出最高相对湿度 plt.text(hum_min_hour+0.15, hum_min+0.15, str(hum_min), ha='center', va='bottom', fontsize=10.5) # 标出最低相对湿度 plt.xticks(x) plt.legend() plt.title('一天相对湿度变化曲线图') plt.xlabel('时间/h') plt.ylabel('百分比/%') plt.show() air = list(data['空气质量']) print(type(air[0])) for i in range(0,24): if math.isnan(air[i]) == True: air[i] = air[i-1] air_ave = sum(air)/24 # 求平均空气质量 air_max = max(air) air_max_hour = hour[air.index(air_max)] # 求最高空气质量 air_min = min(air) air_min_hour = hour[air.index(air_min)] # 求最低空气质量 x = [] y = [] for i in range(0, 24): x.append(i) y.append(air[hour.index(i)]) plt.figure(3) for i in range(0,24): if y[i] <= 50: plt.bar(x[i],y[i],color='lightblue',width=0.9) # 1等级 elif y[i] <= 100: plt.bar(x[i],y[i],color='wheat',width=0.9) # 2等级 elif y[i] <= 150: plt.bar(x[i],y[i],color='red',width=0.9) # 3等级 elif y[i] <= 200: plt.bar(x[i],y[i],color='greenred',width=0.9) # 4等级 elif y[i] <= 300: plt.bar(x[i],y[i],color='darkviolet',width=0.9) # 5等级 elif y[i] > 300: plt.bar(x[i],y[i],color='maroon',width=0.9) # 6等级 plt.plot([0, 24], [air_ave, air_ave], c='black', linestyle='--') # 画出平均空气质量虚线 plt.text(air_max_hour+0.2, air_max+0.2, str(air_max), ha='center', va='bottom', fontsize=10.5) # 标出最高空气质量 plt.text(air_min_hour+0.2, air_min+0.2, str(air_min), ha='center', va='bottom', fontsize=10.5) # 标出最低空气质量 plt.xticks(x) plt.title('一天空气质量变化曲线图') plt.xlabel('时间/h') plt.ylabel('空气质量指数AQI') plt.show()
总结
经过对主题数据的分析与可视化,可以知道该城市在哪某个时间段温度最高,温度最低,以及平均温度,也将湿度,空气质量,风力分析了。从图中也可以看出分布情况。
收获:对于网络爬取越来越了解,操作也越来越熟练。
难点及待改进:难点是在爬取时,在分析网页的源代码时,不能快速地、确切地找到自己想要的获取的代码行,以及对数据可视化的不熟练。
要改进的有在对数据进行具体分析时,没有运用到函数。
小结
通过本学期的python课程学习,更加深入的了解到了python,体验到了它的魅力,但自己对其掌握度还不过,练习的也不够,且还需要对大数据分析,机械学习方面的课程进行深入学习和认识,在后续的学习中还需要加强学习和训练。