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

lykyl的自留地發表於2013-08-22

以前一直使用中國天氣網的天氣預報元件都挺好,可是自從他們升級元件後資料載入變得非常不穩定,因為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、有同學表示,天氣網的外掛不是支援延後載入嗎?嗯,是這樣的。經本人實測在有些手機瀏覽器上會導致整個頁面變空白,問題已提交給官方。

相關文章