\s{1,}
\n\s{1,}(.*?)\s{1,}
'
#寻找出所有的监测值
pm25list = re.compile(data_pm25, re.S).findall(data)
o3list=re.compile(data_o3, re.S).findall(data)
#将臭氧每小时的值插入到原列表中
pm25list.append(o3list[0])
print("AQI指数,PM2.5,PM10,CO,NO2,SO2,O3:(单位:μg/m3,CO为mg/m3)")
print(pm25list)
#将获取到的值写入文件中
writefiles_pm25(city,datatime,pm25list)
#返回数据更新时间值
return datatime
except urllib.error.URLError as e:
print("出现URLERROR!一分钟后重试……")
if hasattr(e,"code"):
print(e.code)
if hasattr(e,"reason"):
print(e.reason)
time.sleep(60)
#出现异常则过一段时间重新执行此部分
getpm25(city)
except Exception as e:
print("出现EXCEPTION!十秒钟后重试……")
print("Exception:"+str(e))
time.sleep(10)
# 出现异常则过一段时间重新执行此部分
getpm25(city)
def writefiles_pm25(filename,datatime,pm25list):
#将获取的数据写入文件中,数据分别为时间,AQI指数,PM2.5,PM10,CO,NO2,SO2,O3。(单位:μg/m3,CO为mg/m3)
f = open("D:\Python\Python35\myweb\data_pm25\data_pm25_"+filename+".txt", "a")
f.write(datatime[0])
f.write(",")
for pm25 in pm25list:
f.write(str(pm25))
f.write(",")
f.write("\n")
print("该条空气质量数据已添加到文件中!")
f.close()
def getweather(city,datatime):
try:
#构建url
url="http://"+city+".tianqi.com/"
data=urllib.request.urlopen(url).read().decode("gbk")
#构建数据收集的表达式
data_weather = '
(.*?)'
data_wind='
(.*?)'
data_temperature='
(.*?)°'
data_humidity='相对湿度:(.*?)'
#寻找出所有的监测值
weatherlist = re.compile(data_weather, re.S).findall(data)
windlist=re.compile(data_wind, re.S).findall(data)
temperaturelist = re.compile(data_temperature, re.S).findall(data)
humiditylist = re.compile(data_humidity, re.S).findall(data)
#将其他值插入到天气列表中
weatherlist.append(windlist[0])
weatherlist.append(temperaturelist[0])
weatherlist.append(humiditylist[0])
print("天气状况,风向风速,实时温度,相对湿度:")
print(weatherlist)
#将获取到的值写入文件中
writefiles_weather(city,datatime,weatherlist)
except urllib.error.URLError as e:
print("出现URLERROR!一分钟后重试……")
if hasattr(e,"code"):
print(e.code)
if hasattr(e,"reason"):
print(e.reason)
time.sleep(60)
# 出现异常则过一段时间重新执行此部分
getweather(city,datatime)
except Exception as e:
print("出现EXCEPTION!十秒钟后重试……")
print("Exception:"+str(e))
time.sleep(10)
# 出现异常则过一段时间重新执行此部分
getweather(city, datatime)
def writefiles_weather(filename,datatime,weatherlist):
#将获取的数据写入文件中,数据分别为时间,天气状况,风向风速,实时温度,相对湿度。
f = open("D:\Python\Python35\myweb\data_weather\data_weather_"+filename+".txt", "a")
f.write(datatime[0])
f.write(",")
for weather in weatherlist:
f.write(str(weather))
f.write(",")
f.write("\n")
print("该条天气数据已添加到文件中!")
f.close()
#退出循环可用Ctrl+C键
while True:
print("开始工作!")
get_pm25_and_weather("beijing")
get_pm25_and_weather("tianjin")
get_pm25_and_weather("shijiazhuang")
get_pm25_and_weather("taiyuan")
get_pm25_and_weather("jinan")
get_pm25_and_weather("shenyang")
get_pm25_and_weather("huhehaote")
get_pm25_and_weather("zhengzhou")
#每一小时执行一次
print("休息中……")
print("\n")
time.sleep(3600)
运行状态图:
更多内容请参考专题《python爬取功能汇总》进行学习。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持中文源码网。