数据可视化指南之数据获取

来源:互联网 发布:ubuntu pyqt4 安装 编辑:程序博客网 时间:2024/06/04 19:23

#-*- encoding:utf-8 -*-import urllib2                          #1from bs4 import BeautifulSoup            #2f = open('temp-data.txt','w')             #3for m in range(1,13):                      #4                                                                                                                        for d in range(1,32):        if (m==2 and d>28):                                                                                                                                                                           #5             break        elif(m in [4,6,9,11] and d>30):                                                                                                                                                               #6            break        timestamp = '2009' + str(m) + str(d)    #7        print "Geting Data for:"+timestamp        url = "http://www.wunderground.com/history/airport/KBUF/2009/" + str(m) + "/" + str(d)+"/DailyHistory.html"     #8        page = urllib2.urlopen(url)                                        #9        soup = BeautifulSoup(page)                                         #10        dayTemp = soup.findAll( attrs = {"class":"wx-value"})[4].string    #11                if len(str(m)) < 2:                                                                                                                                                                                                           #12            mStamp = '0'+str(m)        else:            mStamp = str(m)        if len(str(d)) < 2:            dStamp = '0'+ str(d)        else:            dStamp = str(d)        timestamp = '2009' + mStamp + dStamp                                  #13        f.write(timestamp + ':'+dayTemp + '\n')                               #14f.close()                                                                     #15


</pre><pre>

#1:读取URL要用到的包#2:解析网页的HTML信息用到的包,正在看#3:创建一个文本文件,自动新建#4:想获得一年内每天的最高温度信息,要用for循环,并嵌套了一个for循环,外面是月,里面是天#5:判断2月28天,闰年的话29天,不过2009年不是闰年,要是任意年份的话,可以再改下程序,判断下是否闰年,再加个变量#6判断剩下每月的天数,有的30,有的31,4,6,9,11都是30天,所以到30为止。大于30跳出循环#7外部显示的进度,便于调试纠错#8不同月不同天的URL就两个地方不同#9打开URL#10解析HTML标签#11将class属性为wx-value中的第五个值取出来#12文本内部的时间戳,将如期格式化为时间戳,一位的就前面加0,两位的就不变#13内部的时间戳#14写入文本#15关闭文本,结束

结果:





0 0