2010-06-22

下載中央銀行貨幣總計數M2年增率資料

#!c:/tcl/bin/tclsh86.exe
########################################################################
# 下載中央銀行貨幣總計數M2年增率資料 
########################################################################

package require http

set url "http://www.cbc.gov.tw/np.asp?ctNode=643&mp=1"
set token [http::geturl $url -validate 1]

# create an easy-to-use array variable
upvar #0 $token head

set location "http://www.cbc.gov.tw/"
append location [dict get $head(meta) Location]

puts "### Get file: $location"
http::cleanup $token

set filename "cbc_m1b.xls"

set f [open $filename {WRONLY CREAT EXCL}]
set token [http::geturl $location -channel $f]
http::cleanup $token
close $f

exit

中央銀行貨幣總計數M2年增率資料在首頁就有,只是不是採用直接連結的方式,而是要從 head 裡取得檔案的下載位址,再從下載位址下載。在查過 Tcler's Wiki 該怎麼處理以後,我稍微改寫一下,目前可以正確的從網站下載我需要的資料。

如果中央銀行讓使用者下載資料的位址是固定的,那麼這段 code 就可以一直用下去,如果位址不固定的話,那就要想一下該怎麼做才對。

2010-06-03

下載台灣證券交易所的市值週報

#!c:/tcl/bin/tclsh86.exe
package require http
package require vfs::zip

########################################################################
# Download zip file
########################################################################
set remoteFile "http://www.twse.com.tw/ch/statistics/download/week.zip"
set localFile "week.zip"

set token [::http::geturl $remoteFile -binary 1]
set data [::http::data $token]

set channel [open $localFile w+]
fconfigure $channel -encoding binary -translation binary
puts -nonewline $channel $data
close $channel

::http::cleanup $token

########################################################################
# Now handle zip file
########################################################################
set mnt_file [vfs::zip::Mount $localFile $localFile]
file copy -force [glob $localFile/*] ./
vfs::zip::Unmount $mnt_file $localFile
file delete $localFile

exit

和之前寫的東西很像,使用 http 套件下載檔案,然後使用 vfs::zip 來解 zip 檔。要取得台灣證券交易所的市值週報資料的原因是因為我看到一篇 GDP 與市場大盤的文章,所以想要自己算看看目前的情況。

因為有可能會長期並且以季為單位的進行觀測,所以寫了這個 script,讓自己不用開瀏覽器就拿到資料,應該可以節省一些時間。