- 帖子
- 109
- 主題
- 1
- 精華
- 0
- 積分
- 116
- 點名
- 0
- 作業系統
- win7
- 軟體版本
- 2007
- 閱讀權限
- 20
- 註冊時間
- 2016-8-4
- 最後登錄
- 2018-10-22
 
|
9#
發表於 2016-8-18 17:58
| 只看該作者
回復 1# zyzzyva
補上註解。- #匯入模組(requests需另外安裝,也可使用urllib2)
- import requests
- import time
- import os
- #取得當前日期
- mydate = time.strftime("%Y/%m/%d")
- #將西元年轉為民國年
- year = str(int(mydate[0:4])-1911)
- #將民國年取代日期中之西元年
- mydate2 = mydate.replace(mydate[0:4],year)
- #os.getcwd()取得當前路徑
- setting = os.getcwd() + "\\" + "path.ini"
- #檢查path.ini是否存在,若有則將csv存檔之路徑讀入
- if os.path.exists(setting):
- with open(setting, 'r') as r:
- path = r.read()
- #若csv存檔之資料夾不存在則建立資料夾
- if not os.path.exists(path):
- os.makedirs(path)
- #若path.ini不存在則將path設為空字串
- else:
- path = ""
- #設定header
- headers = {"User-Agent":"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36"}
- #設定url
- url1 = "http://www.twse.com.tw/ch/trading/fund/T86/T86.php"
- #設定post查詢之資料
- payload1 = {"download": "csv",
- "qdate": mydate2,
- "select2": "ALLBUT0999",
- "sorting": "by_issue"}
- #發出request並將網站回覆之資料存入res1變數中
- res1 = requests.post(url1, headers=headers, data=payload1, stream=True)
- #設定csv檔案之路徑與檔名
- fName1 = path + mydate.replace("/","") + ".csv"
- #將res1的資料寫入csv中
- with open(fName1, 'wb') as f1:
- for chunk in res1.iter_content(1024):
- f1.write(chunk)
複製代碼 |
|