基于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

相关文章
相关标签/搜索