#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Phrase stock history
"""
import pandas as pd
import urllib
import sys
import json
import datetime
def getdate():
''' 回傳正確的西元年月日格式 '''
#年
year = datetime.datetime.today().strftime('%Y')
#月
month = datetime.datetime.today().strftime('%m')
#日
day = datetime.datetime.today().strftime('%d')
#年月日
todaydate = year + month + day
return todaydate
if __name__ == "__main__":
#股票代碼
STOCK_NUM = "2330"
ad_date = getdate()
url = 'http://www.twse.com.tw/exchangeReport/STOCK_DAY?date=' + ad_date + '&stockNo=' + STOCK_NUM
#以下是google到的顯示繁中編碼問題,忘記哪邊抓的(有人知道請告訴我,我補上出處)
req = urllib.request.urlopen(url)
encoding = req.headers.get_content_charset()
raw = req.read().decode(encoding).encode(sys.stdin.encoding, 'replace').decode(sys.stdin.encoding)
#把抓到的資料轉成list
raw_list = json.loads(raw)
df = pd.DataFrame.from_records(raw_list['data'], columns=raw_list['fields'])
#存成csv
df.to_csv('Result.csv',index=False,encoding="utf_8_sig")
有時好像會被擋,請謹慎使用


沒有留言:
張貼留言