2012年8月11日 星期六

Python抓取股票代碼

使用Python解析網頁元素抓取股票代碼


觀察證交所提供的股票代碼網頁中,每支股票代碼的網頁標籤以td作為起點,其屬性為bgcolor=#FAFAD2,由於屬性長度為1,所以可將此作為取得每支股票的主要識別起頭。

如上圖所示,如果以屬性bgcolor=#FAFAD2來找我們要的股票代碼勢必會有機會出錯,因為會遇到屬性長度為2的資料,而這並非是我們所要的內容,必須要找出屬性長度為1才是我們要的資料。

故程式依據上述的特性來撰寫,以取得股票代碼。

#!/usr/bin/python
# -*- coding: utf-8 -*-

#---------------------------------------------
#   抓股票代碼
#   Version : 0.1
#   Author : Amin white
#   Release Date : 2012-01-01
#   Python version : 2.7.2
#---------------------------------------------

#引用函式庫
import urllib, sgmllib

def main():
    
    #上市, 上櫃股票代碼網址
    StockType = [2,4]

    for i in range(0, len(StockType)):
        url = "http://brk.twse.com.tw:8000/isin/C_public.jsp?strMode=" + str(StockType[i])  
    
        #解析網頁開始
        webcode = urllib.urlopen(url)
        if webcode.code == 200:
            stock = ParsestrModeWeb().feed(webcode.read())
            webcode.close()            
        
class ParsestrModeWeb(sgmllib.SGMLParser):

    #初始化變數數值
    def reset(self):
        sgmllib.SGMLParser.reset(self)
        self.stockinfo = False
        self.cell = 0 

    #解析網頁標籤為td的內容    
    def start_td(self, attrs):
        if len(attrs) == 1:
            if attrs[0][0] == 'bgcolor' and attrs[0][1] == '#FAFAD2':
                self.stockinfo = True
                self.cell+=1
                self.cell%=7

    #開始讀取股票代碼          
    def handle_data(self, text):
            if self.stockinfo:                
                if self.cell == 1:                   
                    data = text.strip().split("    ")
                    if data[0].isalnum():
                        print data[0].strip()  + " " + data[1].strip()
                self.stockinfo = False
            
if __name__ == "__main__":
    main()

Python執行結果畫面