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

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

代碼以下: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)web

 

注:瀏覽器

一、城市代碼能夠到中國天氣網上去查。網站

二、天氣圖標也能夠在中國天氣網的圖標示例裏去獲取,這裏就不提供了。url

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

相關文章
相關標籤/搜索