2011/03/15

python! 從銀行網頁上抓取匯率並直接寫入MSSQL

需下載LIB:http://pymssql.sourceforge.net/

環境:
python 2.6
mssql 2008

import httplib
from string import split
import pymssql

exchangeURL = "somebank.com.tw"
exchangePage = "/exchange/IP003.zh-TW.htm"

sqlAddr = "192.168.1.200"
sqlAcc = "test"
sqlPasswd = "test"
sqlDBName = "test"
sqlH = "insert into exchangeRate(eR, userrID) values('"
sqlT = " ',12)"
currency = "TWD"

conn = httplib.HTTPConnection(exchangeURL,80)
conn.request("GET",exchangePage)
reader = conn.getresponse()

pageContext = reader.read()
conn.close()
indess = pageContext.find(currency)
pageContext = pageContext[indess:(indess+500)]
exchange = split(split(pageContext,">")[5],"<")[0]
conn.close()

sql = sqlH + exchange + sqlT
cx = pymssql.connect(host=sqlAddr, user=sqlAcc, password=sqlPasswd, database=sqlDBName)
cur = cx.cursor()
cur.execute(sql)
cx.commit()
cur.close()

沒有留言: