本篇 Python 股票與天氣自動化教學專為新手設計,完整介紹 GET 與 POST 請求、JSON 解析與定時排程自動化。內含實務案例與指令範例,讓你能自動抓取股市資料、天氣資訊並更新報表,快速完成股票自動化與天氣自動化操作,節省手動操作時間,提升效率與精準度。
文章目錄
什麼是 API 與用途
API(Application Programming Interface)提供程式間溝通標準。使用 Python 呼叫 API,可自動抓取資料、提交表單與整合第三方服務,應用於天氣自動化、股票自動化、社群自動化或內部系統報表。透過 Python 天氣自動化與 Python 股票自動化,每日可自動更新資訊,節省手動操作,提高精準度與效率。
Python 常用套件
requests:HTTP 請求套件,支援 GET、POST、PUT、DELETEjson:解析 JSON 資料urllib:標準庫處理 URL 與 HTTP 請求schedule:定時排程,可每天自動呼叫 APIpandas:整理資料、篩選股票或天氣資料
GET 範例與指令
# get_example.py
import requests
url = "https://api.example.com/data"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
print(data)
else:
print("取得資料失敗", response.status_code)
# $ python get_example.py
# 備註:GET 用於抓取資料,股票與天氣資料皆可使用 GET
POST 範例與指令
# post_example.py
import requests
url = "https://api.example.com/submit"
payload = {"name": "Alice", "email": "alice@example.com"}
response = requests.post(url, json=payload)
if response.status_code == 200:
print("提交成功", response.json())
else:
print("提交失敗", response.status_code)
# $ python post_example.py
# 備註:POST 用於提交資料或建立資源,例如股票訂單模擬提交
案例:自動抓取天氣資料
# weather_fetch.py
import requests
api_key = "YOUR_API_KEY"
city = "Taipei"
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
response = requests.get(url)
weather = response.json()
print(f"{city} 天氣:{weather['weather'][0]['description']}, 溫度:{weather['main']['temp']}°C")
# $ python weather_fetch.py
# 備註:每日自動抓取天氣資料,可搭配 schedule 或 cron,實現天氣自動化
案例:每日抓匯率資料
# exchange_rate.py
import requests
import schedule
import time
def fetch_exchange_rate():
url = "https://api.exchangerate.host/latest?base=USD"
response = requests.get(url)
rates = response.json()
print("USD 對各貨幣匯率:", rates["rates"])
schedule.every().day.at("09:00").do(fetch_exchange_rate)
while True:
schedule.run_pending()
time.sleep(60)
# $ python exchange_rate.py
# 備註:每日定時抓取匯率,可結合股票或天氣自動化流程
案例:表單提交自動化
# form_submit.py
import requests
url = "https://api.example.com/form"
data = {"username": "testuser", "password": "123456"}
response = requests.post(url, data=data)
if response.status_code == 200:
print("表單提交成功")
else:
print("表單提交失敗")
# $ python form_submit.py
# 備註:自動提交表單,POST 方式
案例:自動抓漲停或成交量大股票
# stock_top5.py
import requests
import pandas as pd
url = "https://www.twse.com.tw/exchangeReport/MI_INDEX?response=json&date=&type=ALL"
response = requests.get(url)
data = response.json()
df = pd.DataFrame(data['data9'], columns=[col[0] for col in data['fields9']])
df['漲跌價差'] = pd.to_numeric(df['漲跌價差'], errors='coerce')
limit_up_stocks = df[df['漲跌價差'] > 0].sort_values(by='漲跌價差', ascending=False).head(5)
df['成交股數'] = pd.to_numeric(df['成交股數'].str.replace(',', ''), errors='coerce')
high_volume_stocks = df.sort_values(by='成交股數', ascending=False).head(5)
print("漲停股票 Top 5:")
print(limit_up_stocks[['證券代號','證券名稱','漲跌價差']])
print("\n成交量大股票 Top 5:")
print(high_volume_stocks[['證券代號','證券名稱','成交股數']])
# $ python stock_top5.py
# 備註:Python 股票自動化範例,定時抓取漲停與成交量大股票
FAQ 常見問題
Python 可以自動抓天氣資料嗎?
可以,搭配 Python 定時排程與 API 呼叫,每日自動抓取天氣資訊,更新報表或系統,即可實現天氣自動化。
Python 可以自動抓股市資料嗎?
可以,使用 Python API 與定時排程抓取漲停或成交量大股票,並整理成報表,自動化追蹤股市資訊。
GET 與 POST 請求差別是什麼?
GET 用於取得資料,不改變伺服器內容;POST 用於提交資料或建立資源,股票訂單或表單提交可使用 POST。
如何解析 JSON 資料?
使用 response.json() 取得 JSON 物件,直接存取欄位,例如 data['key'],適用於天氣資料與股票資料。
如何使用 Python 定時排程自動抓取 API?
使用 schedule 或 cron 設定排程,自動呼叫 API 並處理回傳資料,適用於股票或天氣自動化。
如何處理 API 錯誤或例外?
使用 try-except 捕捉 requests 例外,並依 status_code 進行重試或記錄日誌,確保自動化流程穩定。
