python3爬取各类天气信息


Posted in Python onFebruary 24, 2018

本来是想从网上找找有没有现成的爬取空气质量状况和天气情况的爬虫程序,结果找了一会儿感觉还是自己写一个吧。

主要是爬取北京包括北京周边省会城市的空气质量数据和天气数据。

过程中出现了一个错误:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa1 in position 250。

原来发现是页面的编码是gbk,把语句改成data=urllib.request.urlopen(url).read().decode("gbk")就可以了。

然后我把爬到的数据写到文本文档里了,往后可以导入到excel表中使用。

实验室的电脑不经常开,然后就放到服务器上了,让它自己慢慢一小时爬一次吧~哈哈哈~

后面有一次晚上出现了异常,因为没加入异常处理,所以从零点到早上五点的数据都没爬到。。。

(⊙?⊙)然后这次修改就加入了异常处理。如果出现URLError,就一分钟后重试。

代码:

#coding=utf-8 
#北京及周边省会城市污染数据、天气数据每小时监测值爬虫程序 
import urllib.request 
import re 
import urllib.error 
import time 
#模拟成浏览器 
headers=("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36") 
opener = urllib.request.build_opener() 
opener.addheaders=[headers] 
#将opener安装为全局 
urllib.request.install_opener(opener) 
def get_pm25_and_weather(city): 
 #首先执行获取空气质量数据,返回数据更新时间 
 data_time=getpm25(city) 
 #然后将获取到的数据更新时间赋值给获取天气数据函数使用 
 getweather(city,data_time) 
def getpm25(city): 
 try: 
 #设置url地址 
 url="http://pm25.in/"+city 
 data=urllib.request.urlopen(url).read().decode("utf-8") 
 print("城市:"+city) 
 #构建数据更新时间的表达式 
 data_time='<div class="live_data_time">\s{1,}<p>数据更新时间:(.*?)</p>' 
 #寻找出数据更新时间 
 datatime=re.compile(data_time, re.S).findall(data) 
 print("数据更新时间:"+datatime[0]) 
 #构建数据收集的表达式 
 data_pm25 = '<div class="span1">\s{1,}<div class="value">\n\s{1,}(.*?)\s{1,}</div>' 
 data_o3='<div class="span1">\s{1,}<div class ="value">\n\s{1,}(.*?)\s{1,}</div>' 
 #寻找出所有的监测值 
 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 = '<li class="cDRed">(.*?)</li>' 
 data_wind='<li style="height:18px;overflow:hidden">(.*?)</li>' 
 data_temperature='<div id="rettemp"><strong>(.*?)°' 
 data_humidity='</strong><span>相对湿度:(.*?)</span>' 
 #寻找出所有的监测值 
 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)

运行状态图:

python3爬取各类天气信息

更多内容请参考专题《python爬取功能汇总》进行学习。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python list转dict示例分享
Jan 28 Python
在Python的Django框架中实现Hacker News的一些功能
Apr 17 Python
Python随手笔记第一篇(2)之初识列表和元组
Jan 23 Python
python实现二叉查找树实例代码
Feb 08 Python
使用python3+xlrd解析Excel的实例
May 04 Python
Python 实例方法、类方法、静态方法的区别与作用
Aug 14 Python
Python 基于wxpy库实现微信添加好友功能(简洁)
Nov 29 Python
python logging 日志的级别调整方式
Feb 21 Python
利用python对mysql表做全局模糊搜索并分页实例
Jul 12 Python
python中scrapy处理项目数据的实例分析
Nov 22 Python
python中threading和queue库实现多线程编程
Feb 06 Python
浅析Python OpenCV三种滤镜效果
Apr 11 Python
python opencv之SIFT算法示例
Feb 24 #Python
python3 破解 geetest(极验)的滑块验证码功能
Feb 24 #Python
python opencv之SURF算法示例
Feb 24 #Python
几种实用的pythonic语法实例代码
Feb 24 #Python
使用Python爬取最好大学网大学排名
Feb 24 #Python
python opencv 直方图反向投影的方法
Feb 24 #Python
python爬虫爬取淘宝商品信息
Feb 23 #Python
You might like
如何用PHP实现插入排序?
2013/04/10 PHP
laravel学习教程之存取器
2016/07/30 PHP
详解PHP中foreach的用法和实例
2016/10/25 PHP
PHP使用第三方即时获取物流动态实例详解
2017/04/27 PHP
浅谈Laravel中的一个后期静态绑定
2017/08/11 PHP
javascript Zifa FormValid 0.1表单验证 代码打包下载
2007/06/08 Javascript
jQuery 学习第五课 Ajax 使用说明
2010/05/17 Javascript
基于jQuery的的一个隔行变色,鼠标移动变色的小插件
2010/07/06 Javascript
Jquery 自定义动画概述及示例
2013/03/29 Javascript
JS获取网页图片name属性的方法
2015/04/01 Javascript
Javascript动态创建表格及删除行列的方法
2015/05/15 Javascript
JQuery判断checkbox是否选中及其它复选框操作方法合集
2015/06/01 Javascript
Bootstrap表单组件教程详解
2016/04/26 Javascript
Bootstrap基本组件学习笔记之面板(14)
2016/12/08 Javascript
微信小程序 开发MAP(地图)实例详解
2017/06/27 Javascript
JS对象与JSON互转换、New Function()、 forEach()、DOM事件流等js开发基础小结
2017/08/10 Javascript
ES6扩展运算符用法实例分析
2017/10/31 Javascript
简单了解JavaScript中的执行上下文和堆栈
2019/06/24 Javascript
原生Vue 实现右键菜单组件功能
2019/12/16 Javascript
图解JS原型和原型链实现原理
2020/09/15 Javascript
python使用mysqldb连接数据库操作方法示例详解
2013/12/03 Python
详解Python中用于计算指数的exp()方法
2015/05/14 Python
pandas数据框,统计某列数据对应的个数方法
2018/04/11 Python
对python模块中多个类的用法详解
2019/01/10 Python
python读取csv文件指定行的2种方法详解
2020/02/13 Python
DRF框架API版本管理实现方法解析
2020/08/21 Python
pytorch中index_select()的用法详解
2021/01/06 Python
Python使用pyenv实现多环境管理
2021/02/05 Python
使用python实现学生信息管理系统
2021/02/25 Python
机械设计制造专业个人求职信
2013/09/25 职场文书
应届毕业生自我评价分享
2013/12/15 职场文书
工作时间上网检讨书
2014/02/03 职场文书
总经理助理岗位职责范本
2014/07/20 职场文书
2014年音乐教师工作总结
2014/12/03 职场文书
财务人员廉洁自律心得体会
2016/01/13 职场文书
Django中的JWT身份验证的实现
2021/05/07 Python