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实现的金山快盘的签到程序
Jan 17 Python
Python实现的堆排序算法原理与用法实例分析
Nov 22 Python
Python3导入自定义模块的三种方法详解
Apr 13 Python
Python文本统计功能之西游记用字统计操作示例
May 07 Python
解决安装python3.7.4报错Can''t connect to HTTPS URL because the SSL module is not available
Jul 31 Python
Python 实现加密过的PDF文件转WORD格式
Feb 04 Python
对tensorflow中cifar-10文档的Read操作详解
Feb 10 Python
Python爬虫如何应对Cloudflare邮箱加密
Jun 24 Python
Python利用matplotlib绘制散点图的新手教程
Nov 05 Python
python的scipy.stats模块中正态分布常用函数总结
Feb 19 Python
Django给表单添加honeypot验证增加安全性
May 06 Python
python中字符串String及其常见操作指南(方法、函数)
Apr 06 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生成静态页面分析 模板+缓存+写文件
2009/08/17 PHP
PHP 缓存实现代码及详细注释
2010/05/16 PHP
php 冒泡排序 交换排序法
2011/05/10 PHP
php _autoload自动加载类与机制分析
2012/02/10 PHP
php preg_replace替换实例讲解
2013/11/04 PHP
高性能PHP框架Symfony2经典入门教程
2014/07/08 PHP
PHP代码重构方法漫谈
2018/04/17 PHP
thinkPHP5框架闭包函数与子查询传参用法示例
2018/08/02 PHP
PHP bin2hex()函数基础实例讲解
2019/02/11 PHP
对 lightbox JS 图片控件进行了一下改造, 使其他支持复杂的图片说明
2010/03/20 Javascript
Jquery Ajax的Get方式时需要注意URL地方
2011/04/07 Javascript
javascript向flash swf文件传递参数值注意细节
2012/12/11 Javascript
基于JavaScript 数据类型之Boolean类型分析介绍
2013/04/19 Javascript
当前页禁止复制粘贴截屏代码小集
2013/07/24 Javascript
通过action传过来的值在option获取进行验证的方法
2013/11/14 Javascript
nodejs 实现模拟form表单上传文件
2014/07/14 NodeJs
JavaScript添加随滚动条滚动窗体的方法
2016/02/23 Javascript
jQuery实现点击任意位置弹出层外关闭弹出层效果
2016/10/19 Javascript
Angular JS 生成动态二维码的方法
2017/02/23 Javascript
小程序实现留言板
2018/11/02 Javascript
实例详解带参数的 npm script
2019/05/28 Javascript
bootstrap table插件动态加载表头
2019/07/19 Javascript
弱类型语言javascript中 a,b 的运算实例小结
2019/08/07 Javascript
js实现移动端tab切换时下划线滑动效果
2019/09/08 Javascript
JavaScript设计模型Iterator实例解析
2020/01/22 Javascript
[30:55]完美世界DOTA2联赛PWL S2 Magma vs LBZS 第二场 11.18
2020/11/18 DOTA
PyQt5每天必学之事件与信号
2018/04/20 Python
Python中出现IndentationError:unindent does not match any outer indentation level错误的解决方法
2020/04/18 Python
对PyQt5基本窗口控件 QMainWindow的使用详解
2019/06/19 Python
学python安装的软件总结
2019/10/12 Python
Python爬虫requests库多种用法实例
2020/05/28 Python
Python中过滤字符串列表的方法
2020/12/22 Python
西门豹教学反思
2014/02/04 职场文书
高校教师自荐信范文
2014/03/13 职场文书
教师专业自荐信
2014/05/31 职场文书
MySQL里面的子查询的基本使用
2021/08/02 MySQL