侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

python3爬取各类天气信息

Python  /  管理员 发布于 7年前   177

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

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

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

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

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

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

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

(⊙n⊙)然后这次修改就加入了异常处理。如果出现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) 

运行状态图:

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

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


  • 上一条:
    python opencv之分水岭算法示例
    下一条:
    python opencv之SIFT算法示例
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客