国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python3爬取各類天氣信息

2020-01-04 15:47:47
字體:
來源:轉載
供稿:網友

本來是想從網上找找有沒有現成的爬取空氣質量狀況和天氣情況的爬蟲程序,結果找了一會兒感覺還是自己寫一個吧。

主要是爬取北京包括北京周邊省會城市的空氣質量數據和天氣數據。

過程中出現了一個錯誤: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,爬取,天氣信息

 

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。


注:相關教程知識閱讀請移步到python教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 阜平县| 徐州市| 莫力| 双辽市| 天气| 平湖市| 黑龙江省| 绍兴市| 潜山县| 剑阁县| 台安县| 岳普湖县| 句容市| 枝江市| 漠河县| 黄山市| 清苑县| 布拖县| 平和县| 莫力| 屯留县| 浠水县| 定西市| 安义县| 钟祥市| 武穴市| 泗水县| 万宁市| 温泉县| 安塞县| 钟山县| 老河口市| 平南县| 开鲁县| 旬邑县| 泗阳县| 大田县| 霍州市| 土默特左旗| 济源市| 衡南县|