• 基于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")+'"); ')
          fp.write('//'+now.strftime('%Y-%m-%d %H:%M:%S')+' ')
          fp.close()
        except IOError:
          print "ioerror"

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

    注:

    1、城市代码可以到中国天气网上去查。

    2、天气图标也可以在中国天气网的图标示例里去获取,这里就不提供了。

    3、有同学表示,天气网的插件不是支持延后加载吗?嗯,是这样的。经本人实测在有些手机浏览器上会导致整个页面变空白,问题已提交给官方。

  • 相关阅读:
    idea 安装lombok 插件过程
    typora快捷键之速成笔记
    Android端抓取日志
    接口测试Case之面向页面对象编写及规范
    Jenkins + jmeter + ant + git 自动化集成
    自动化测试使用流程
    Jenkins git 的配置及问题解决
    传智springMVC笔记
    session 原理 数据结构
    Redis 3.0 集群搭建
  • 原文地址:https://www.cnblogs.com/lykyl/p/3274458.html
Copyright © 2020-2023  润新知