# 如何獲得上市上櫃股票清單
import requests
import time
import pandas as pd
from sqlalchemy import create_engine
from sqlalchemy.types import NVARCHAR, Date
def getTWSE(str_mode):
# 設定爬蟲程式的 User_Agent
headers = {'user-agent': 'Mozilla/5.0 (Macintosh Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36'}
# 上市: http://isin.twse.com.tw/isin/C_public.jsp?strMode=2
# 上櫃: http://isin.twse.com.tw/isin/C_public.jsp?strMode=4
req_url = "http://isin.twse.com.tw/isin/C_public.jsp?strMode=%s" % (str_mode)
res = requests.get(req_url, headers=headers)
df = pd.read_html(res.text)[0]
# 設定column名稱
df.columns = df.iloc[0]
# 刪除第一行
df = df.iloc[1:]
# 先移除row,再移除column,超過三個NaN則移除
df = df.dropna(thresh=3, axis=0).dropna(thresh=3, axis=1)
df[['有價證券代號','名稱']] = df['有價證券代號及名稱'].str.split(n=1, expand=True)
del df['有價證券代號及名稱']
df = df.set_index('有價證券代號')
return df
engine = create_engine("mysql+pymysql://stockuser:password@127.0.0.1:3306/stockdb")
dtypedict = {
'有價證券代號':NVARCHAR(length=32),
'上市日': Date()
}
# 抓取上市公司股票清單, 寫入MySQL > stockdb > listed_code (listed_code table存在時整個取代)
listed_companies = "2" #上市公司
mydf1 = getTWSE(listed_companies)
mydf1.to_sql(name="listed_code", con=engine, if_exists = 'replace', index=True, dtype=dtypedict)
# 先睡個10秒鐘吧
time.sleep(10)
# 抓取上櫃公司股票清單, 寫入MySQL > stockdb > listed_code (append 到 listed_code table)
listed_companies = "4" #上櫃公司
mydf2 = getTWSE(listed_companies)
mydf2.to_sql(name="listed_code", con=engine, if_exists = 'append', index=True, dtype=dtypedict)
2019年4月30日 星期二
python 抓取上市及上櫃公司清單, 並寫入 MySQL 資料庫
不囉嗦,直接看程式碼:
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言