---
# System prepended metadata

title: 自動抓取天氣資料
tags: [windows自動排程, 讀書會]

---

# 自動抓取天氣資料
###### tags: `讀書會` `windows自動排程`
每小時會更新一筆資料:https://opendata.cwb.gov.tw/api/v1/rest/datastore/O-A0001-001?Authorization=rdec-key-123-45678-011121314

## 抓取資料程式:
<pre>import requests
import json
import csv
url = "https://opendata.cwb.gov.tw/api/v1/rest/datastore/O-A0001-001?Authorization=rdec-key-123-45678-011121314"
req = requests.get(url)  # method:get  去到頁面
json_content = req.content.decode('utf-8')
jason_dict = json.loads(json_content)
with open("C:/Users/ur08354/Desktop/python/weatherdata/" + jason_dict['records']['location'][0]['time']['obsTime'].replace(':','_') + ".csv", "w", newline='') as f:
    writer = csv.writer(f)
    writer.writerow(['觀測站', '氣溫', '風向', '風速'])
    for location in jason_dict['records']['location']:
        writer.writerow([location['locationName'], location['weatherElement'][3]['elementValue'], location['weatherElement'][1]['elementValue'], location['weatherElement'][2]['elementValue'] ])</pre>
## 執行天氣爬蟲的批次檔:
<pre>
cd/d D:\basic_nlp_demo
call python weather_crawler.py
REM pause
</pre>
## 使用windows工作排程設定執行時間:
參考網址:https://titangene.github.io/article/set-up-windows-task-scheduler-to-periodically-execute-python-crawler.html
## 讀取資料夾內的所有CSV檔:
<pre>
import os
items = os.listdir("C:/Users/ur08354/Desktop/python/weatherdata")
csvlist = []
for names in items:
    if names.endswith(".csv"):
        csvlist.append(names)
print(csvlist)
</pre>