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警察与小偷的实现之一客户端与服务端通信实例
Oct 09 Python
数组保存为txt, npy, csv 文件, 数组遍历enumerate的方法
Jul 09 Python
详解django中使用定时任务的方法
Sep 27 Python
在django admin中添加自定义视图的例子
Jul 26 Python
pytorch中torch.max和Tensor.view函数用法详解
Jan 03 Python
Python reduce函数作用及实例解析
May 08 Python
tensorflow下的图片标准化函数per_image_standardization用法
Jun 30 Python
python接入支付宝的实例操作
Jul 20 Python
记录一下scrapy中settings的一些配置小结
Sep 28 Python
python爬虫工具例举说明
Nov 30 Python
python中的被动信息搜集
Apr 29 Python
python爬虫请求库httpx和parsel解析库的使用测评
May 10 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 编程请选择正确的文本编辑软件
2006/12/21 PHP
Yii入门教程之目录结构、入口文件及路由设置
2014/11/25 PHP
PHP 进度条函数的简单实例
2017/09/19 PHP
PHP基于自定义函数实现的汉字转拼音功能实例
2017/09/30 PHP
ExtJS4 Grid改变单元格背景颜色及Column render学习
2013/02/06 Javascript
JavaScript通过代码调用Flash显示的方法
2016/02/02 Javascript
JS实现随机颜色的3种方法与颜色格式的转化
2017/01/05 Javascript
老生常谈jacascript DOM节点获取
2017/04/17 Javascript
React中jquery引用的实现方法
2017/09/12 jQuery
关于Vue单页面骨架屏实践记录
2017/12/13 Javascript
使用vuex解决刷新页面state数据消失的问题记录
2019/05/08 Javascript
ES6基础之 Promise 对象用法实例详解
2019/08/22 Javascript
[04:54]DOTA2-DPC中国联赛1月31日Recap集锦
2021/03/11 DOTA
python33 urllib2使用方法细节讲解
2013/12/03 Python
Python 结巴分词实现关键词抽取分析
2017/10/21 Python
python操作oracle的完整教程分享
2018/01/30 Python
python中字符串比较使用is、==和cmp()总结
2018/03/18 Python
Python 字符串、列表、元组的截取与切片操作示例
2019/09/17 Python
Pytorch通过保存为ONNX模型转TensorRT5的实现
2020/05/25 Python
详解Selenium 元素定位和WebDriver常用方法
2020/12/04 Python
草莓巧克力:Shari’s Berries
2017/02/07 全球购物
Monnier Freres中文官网:法国领先的奢侈品配饰在线零售商
2017/11/01 全球购物
欧洲最大的预定车位市场:JustPark
2020/01/06 全球购物
一份比较全的PHP面试题
2016/07/29 面试题
中专生自我鉴定范文
2013/12/19 职场文书
预备党员思想汇报范文
2014/01/11 职场文书
二年级数学教学反思
2014/01/21 职场文书
法学个人求职信范文
2014/01/27 职场文书
服装设计师职业生涯规划范文
2014/02/28 职场文书
个人授权委托书范本
2014/04/03 职场文书
道路运输企业安全生产责任书
2014/07/28 职场文书
2015年元旦促销方案书
2014/12/09 职场文书
企业办公室主任岗位职责
2015/04/01 职场文书
单位更名证明
2015/06/18 职场文书
Nginx解决403 forbidden的完整步骤
2021/04/01 Servers
如何用JavaScript学习算法复杂度
2021/04/30 Javascript