【Python數據分析】從Web收集數據小實例


最近在看《鮮活的數據:數據可視化指南》,學習一些數據可視化與數據分析的技術,本例是該書第一章的一個例子衍伸而來。

實例內容:從www.wunderground.com收集美國紐約州布法羅市(水牛城)2014年3月份每天最高氣溫,並導入Excel或WPS表格,制做成折線圖。

 

工具准備:安裝好的Python2.7,Beautiful Soup庫(將其python文件放入Python庫文件路徑中)

 

步驟1:撰寫Python程序。代碼如下:

# -*- coding: cp936 -*-
import urllib2 from BeautifulSoup import BeautifulSoup f = open('wunder-data.txt','w')     #open the file
 m = 3                               #get weather data of March(3) 2014
for d in range(1,32):               #loop from 2014.3.1 to 2014.3.31
 timestamp = '2014' + str(m) + str(d) print "Getting data for " + timestamp   #for we can see the process in shell
    url = "http://www.wunderground.com/history/airport/KBUF/2014/" + str(m) + "/" + str(d) + "/DailyHistory.html" page = urllib2.urlopen(url)     #get the web page
 soup = BeautifulSoup(page)      #use BeautifulSoup to parsing the web page
 dayTemp = soup.findAll(attrs = {"class":"nobr"})[4].span.string   #the data is showed in some HTML code where <class = "nobr">s are appeared 

    if len(str(m)) < 2:             #format it
        mStamp = '0' + str(m) else: mStamp = str(m) if len(str(d)) < 2:             #format it
        dStamp = '0' + str(d) else: dStamp = str(d) timestamp = '2014-' + mStamp + '-' + dStamp  #make data look like 2014-03-01,which is convinient for excel or WPS to deal with
 f.write(timestamp + ',' + dayTemp + '\n')   #write it to the file
f.close()                           #close the file

 

步驟2:運行程序,得到數據文件wunder-data.txt。

步驟3:將數據導入WPS或Excel中,我用的是WPS表格:數據->導入數據->.....(這里就不貼圖了)

步驟4:圖表制作。

結果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM