hao0089 发表于 2015-4-21 08:13:20

基于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=""+Items.split(":")+" "+Items.split(":")+" "+Items.split(":")+" / "+Items.split(":")+" "+" "
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、有同学表示,天气网的插件不是支持延后加载吗?嗯,是这样的。经本人实测在有些手机浏览器上会导致整个页面变空白,问题已提交给官方。
页: [1]
查看完整版本: 基于python编写的天气抓取程序