Python取得天气预报的一个例子(南京)

经常需要知道最近的天气情况,当然,目前有许多查看天气预报的方式,比如QQ天气等,不过我们也可以自已写一个,体验一下DIY的乐趣,呵呵。本文主要介绍的是使用Python的urllib从天气预报网站抓取预报内容的方法,如果你在南京,那下面的代码可以直接使用(除非抓取的网站改版)。

废话少说,上代码:

#  -*- coding: utf-8 -*-
import  urllib
import  re

def  getWF():
    url 
=   " http://www.jlweather.com/nanjing_map.asp "
    
print   " ] downloading the page from " , url
    u 
=  urllib.urlopen(url)
    page_content 
=   ""
    
while   1 :
        line 
=  u.readline()
        
if  len(line)  ==  0:
            
break
        page_content 
+=  line
    u.close()
    
print   " ] page has been downloaded, analyse starting ... "
    idx 
=  page_content.index( " 南京市气象局今天 " )
    p 
=  page_content[idx:]
    idx 
=  p.index( " </font> " )
    p 
=  p[:idx]
    p 
=  re.sub(r "  + " "" , p)
    
print
    
print  p

    f 
=  open( " weatherForecast_NJ.txt " " w+ " )
    f.write(p)
    f.close()

if   __name__   ==   " __main__ " :
    
print   " ] Show the last report saved in local device. "
    
try :
        f 
=  open( " weatherForecast_NJ.txt " " r " )
        s 
=  f.read()
        
print
        
print  s
        f.close()
    
except :
        
print   " ] no report file is found here! "
    
print
    
print   " ] Now get the weather forecast of Nanjing. "
    getWF()
    
print   " ] done! "
    
# print "] press Enter to quite.",
     # raw_input()

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值