1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | import requests import urllib3 import json # 關閉 InsecureRequestWarning urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) url = 'https://data.moa.gov.tw/Service/OpenData/FromM/AquaticTransData.aspx' r = requests.get(url, verify=False) # 檢查 HTTP 狀態 if r.status_code != 200: print(f"資料取得失敗,HTTP 狀態碼:{r.status_code}") else: try: text = json.loads(r.text) for row in text: # 有些資料可能沒有「魚貨名稱」或「市場名稱」,需先檢查鍵存在 if '魚貨名稱' in row and '市場名稱' in row: if '吳郭魚' in row['魚貨名稱'] and '斗南' in row['市場名稱']: print('交易日期:' + str(row.get('交易日期', '無資料'))) print('品種代碼:' + str(row.get('品種代碼', '無資料'))) print('魚貨名稱:' + str(row.get('魚貨名稱', '無資料'))) print('市場名稱:' + str(row.get('市場名稱', '無資料'))) print('上價:' + str(row.get('上價', '無資料'))) print('中價:' + str(row.get('中價', '無資料'))) print('下價:' + str(row.get('下價', '無資料'))) print('交易量:' + str(row.get('交易量', '無資料'))) print('平均價:' + str(row.get('平均價', '無資料'))) print('-' * 40) except json.JSONDecodeError as e: print("JSON 解析錯誤:", e) except Exception as e: print("發生錯誤:", e) |
執行結果: 交易日期:1141109 品種代碼:1011 魚貨名稱:吳郭魚 市場名稱:斗南 上價:76.0 中價:63.6 下價:51.9 交易量:1631.0 平均價:63.8 ---------------------------------------- 交易日期:1141108 品種代碼:1011 魚貨名稱:吳郭魚 市場名稱:斗南 上價:76.7 中價:74.8 下價:72.5 交易量:1751.3 平均價:74.7 ---------------------------------------- 交易日期:1141107 品種代碼:1011 魚貨名稱:吳郭魚 市場名稱:斗南 上價:76.0 中價:66.6 下價:52.0 交易量:1636.3 平均價:65.6 ---------------------------------------- 交易日期:1141106 品種代碼:1011 魚貨名稱:吳郭魚 市場名稱:斗南 上價:76.0 中價:67.2 下價:59.3 交易量:1643.7 平均價:67.4 ---------------------------------------- 交易日期:1141105 品種代碼:1011 魚貨名稱:吳郭魚 市場名稱:斗南 上價:76.0 中價:63.4 下價:56.0 交易量:1593.1 平均價:64.5 ---------------------------------------- 交易日期:1141104 品種代碼:1011 魚貨名稱:吳郭魚 市場名稱:斗南 上價:76.0 中價:70.8 下價:63.6 交易量:1812.5 平均價:70.4 ---------------------------------------- 交易日期:1141102 品種代碼:1011 魚貨名稱:吳郭魚 市場名稱:斗南 上價:76.0 中價:64.0 下價:48.8 交易量:1704.5 平均價:63.4 ---------------------------------------- 交易日期:1141101 品種代碼:1011 魚貨名稱:吳郭魚 市場名稱:斗南 上價:76.0 中價:69.5 下價:58.1 交易量:1790.1 平均價:68.5 ----------------------------------------
沒有留言:
張貼留言