通过网站:http://www.tianqihoubao.com/ 可以查询各个城市从2011-01至今的历史天气预报,发现诸如date_url='http://www.tianqihoubao.com/lishi/shanghai/month/201101.html' ,可以打开包含上海2011-01月份历史天气预报信息的网页。
尝试使用python打开网页,代码如下:
import requests date_url='http://www.tianqihoubao.com/lishi/shanghai/month/201101.html' user_agent = r'Mozilla/5.0 (Windows NT 10.0; Win64;x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3724.8 Safari/537.36' header = { 'Content-Type':'application/x-www-form-urlencoded', 'User-Agent':user_agent, 'Connection': 'keep-alive', } r = requests.post(url=date_url, headers=header) print(r.text)
发现网页使用table存放天气信息,如下:
<table width="100%" border="0" class="b" cellpadding="1" cellspacing="1"> <tr> <td> <b>日期</b></td> <td> <b>天气状况</b></td> <td> <b>气温</b></td> <td> <b>风力风向</b></td> </tr> <tr> <td> <a href='/lishi/shanghai/20110101.html' title="2011年01月01日上海天气预报"> 2011年01月01日 </a> </td> <td> 晴 /多云</td> <td> 4℃ / 0℃ </td> <td> 西北风 4-5级 /北风 4-5级</td> </tr> <tr> <td> <a href='/lishi/shanghai/20110102.html' title="2011年01月02日上海天气预报"> 2011年01月02日 </a> </td> <td> 多云 /雨夹雪</td> <td> 6℃ / 2℃ </td> <td> 北风 4-5级 /北风 4-5级</td> </tr>
因此使用正则表达式提取出来,并通过xlwt将数据存放至xls文件。
代码实现
import re import requests import xlwt workbook=xlwt.Workbook() #新建工作簿 sheet=workbook.add_sheet('数据') user_agent = r'Mozilla/5.0 (Windows NT 10.0; Win64;x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3724.8 Safari/537.36' header = { 'Content-Type':'application/x-www-form-urlencoded', 'User-Agent':user_agent, 'Connection': 'keep-alive', } #定义正则表达式 p1=r'<table (.*?)>(.*?)</table>' pattern1 = re.compile(p1,re.M|re.S) p2=r'<tr>(.*?)</tr>' pattern2 = re.compile(p2,re.M|re.S) p3=r'<td>(.*?)</td>' pattern3 = re.compile(p3,re.M|re.S) p4=r'">(.*?)<' pattern4 = re.compile(p4,re.M|re.S) count=0 for year in range(2011,2020): for month in range(1,13): print(year,month) if(year==2019 and month==11):#结束程序 workbook.save('a.xls') print('done') break date_url='http://www.tianqihoubao.com/lishi/shanghai/month/' if(month<10): date_url=date_url+str(year)+'0'+str(month)+'.html' else: date_url=date_url+str(year)+str(month)+'.html' r = requests.post(url=date_url, headers=header) #获得原始网页文本 html_doc=r.text #获得天气表格 matcher1 = re.findall(pattern1,html_doc) month_weather_text=matcher1[0][1] #获得每天的天气文本 matcher2 = re.findall(pattern2,month_weather_text) for one_day_weather in matcher2[1:]: #获得当天的日期文本 matcher3 = re.findall(pattern3,one_day_weather) day_raw_text=matcher3[0] matcher4 = re.findall(pattern4,day_raw_text) day_text=matcher4[0].strip() #获得当天的天气 weather_text=matcher3[1].strip().replace(' ','').replace('\r\n','') #获得当天的温度 temperature_text=matcher3[2].strip().replace(' ','').replace('\r\n','') #获得当天的风向和风力 wind_text=matcher3[3].strip().replace(' ','').replace('\r\n','') #写入excel sheet.write(count,0,day_text) sheet.write(count,1,weather_text) sheet.write(count,2,temperature_text) sheet.write(count,3,wind_text) count+=1
运行得到2011-01-01至今三千多天的天气预报记录: