本来是想从网上找找有没有现成的爬取空气质量状况和天气情况的爬虫程序,结果找了一会儿感觉还是自己写一个吧。
主要是爬取北京包括北京周边省会城市的空气质量数据和天气数据。
过程中出现了一个错误: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>数据更新时间:(.*"数据更新时间:"+datatime[0]) #构建数据收集的表达式 data_pm25 = '<div class="span1">\s{1,}<div class="value">\n\s{1,}(.*"span1">\s{1,}<div class ="value">\n\s{1,}(.*"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">(.*"height:18px;overflow:hidden">(.*"rettemp"><strong>(.*"天气状况,风向风速,实时温度,相对湿度:") 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爬取功能汇总》进行学习。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com
暂无评论...
RTX 5090要首发 性能要翻倍!三星展示GDDR7显存
三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。
首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。
据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。
更新日志
2024年09月21日
2024年09月21日
- 魔兽世界阿奴巴拉克有什么背景故事 阿奴巴拉克背景故事介绍
- NeilYoung-EarlyDaze(2024)[24Bit]WAV
- NeaveTrio-Rooted(2024)[24Bit-WAV]
- [吉他演奏]RCAREDSEAL《Rodrigo-ConciertoDeAranjues》[WAV+CUE]
- 气质绝了!《黑神话》蜘蛛四妹演员COS自己正片释出
- 《黑神话:悟空》第五章动画大闹天宫内容被删:牛魔王是主角
- 玩家吐槽《黑神话》如意金箍棒属性差:就该是最强武器
- 《邓紫棋 上古情歌2CD》[WAV/分轨][1.1GB]
- 崔健《摇滚交响音乐会 2CD》[WAV/分轨][730MB]
- 群星《顶级发烧大碟 蒙面歌王争霸战 2CD》[WAV/分轨][1.3GB]
- 群星.2009-原班情歌2CD【SONY】【WAV+CUE】
- 群星.2024-长乐曲电视剧原声带【TME影音】【FLAC分轨】
- 群星.1993-烧得厉害VOL.1好戏好歌唱不停【滚石】【WAV+CUE】
- 魔兽世界wlk阿奴巴拉克怎么打 wlk阿奴巴拉克机制与打法
- 归龙潮阿律的笛子位置在哪 阿律的笛子图文位置一览