基於python編寫的天氣抓取程序


以前一直使用中國天氣網的天氣預報組件都挺好,可是自從他們升級組件后數據加載變得非常不穩定,因為JS的阻塞常常導致網站打開速度很慢。為了解決這個問題決定現學現用python編寫一個抓取程序,每天定時抓取最新的天氣情況並生成靜態JS供網站調用。由於初學python,程序有些地方寫得不是很優雅,還望高手指正。

代碼如下:

#!/usr/bin/env python
#coding:UTF-8

import urllib,os,datetime

def GetWeather(cityid):
  "獲取指定城市的天氣情況"
  #http://www.weather.com.cn/data/cityinfo/101110301.html
  #{"weatherinfo":{"city":"延 長","cityid":"101110301","temp1":"31℃","temp2":"18℃","weather":"多 雲","img1":"d1.gif","img2":"n1.gif","ptime":"08:00"}}
  url="http://www.weather.com.cn/data/cityinfo/"+cityid+".html"
  Result=""
  try:
    web=urllib.urlopen(url)
    content=web.read().decode('utf-8').replace('"',"")
  except Exception,e:
    Result="error"
  if content.find("{weatherinfo") >=0:
    Items=content.replace("{weatherinfo:{","").replace("}}","").split(",")
    if len(Items)>=8:
      Result="<span class='weather'>"+Items[0].split(":")[1]+"&nbsp;"+Items[4].split(":")[1]+"&nbsp;"+Items[2].split(":")[1]+"&nbsp;/&nbsp;"+Items[3].split(":")[1]+"&nbsp;</span><img src='/images/weather/"+Items[5].split(":")[1]+"'>"+"&nbsp;<img src='/images/weather/"+Items[6].split(":")[1]+"'>"
  return Result

def CreateJS(FileName,Content):
  if len(Content)>10:
    now=datetime.datetime.now()
    try:
      fp=open(FileName,'w')
      fp.write('document.write("'+Content.encode("utf-8")+'");\n')
      fp.write('//'+now.strftime('%Y-%m-%d %H:%M:%S')+'\n')
      fp.close()
    except IOError:
      print "ioerror"

if __name__ == "__main__":
  Wcont=GetWeather("101110301")
  #print Wcont
  CreateJS("/weather.js",Wcont)

 

注:

1、城市代碼可以到中國天氣網上去查。

2、天氣圖標也可以在中國天氣網的圖標示例里去獲取,這里就不提供了。

3、有同學表示,天氣網的插件不是支持延后加載嗎?嗯,是這樣的。經本人實測在有些手機瀏覽器上會導致整個頁面變空白,問題已提交給官方。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM