![]() |
羅德興老師的教學歷程檔案 - 113-2 程式語言二(2025) - 單元七 (大數據處理) |
|
|
單元七 (大數據處理)歡迎使用 中華科技大學e-Portfolio系統. 試著寫篇文章吧!.""" 這支程式檔名 bigdata0.ipynb 由 學號 xxxx000 羅老師 所撰寫 on 2025/05/04 功能為 能即時取得 台銀牌告匯率, 包括: 即時擷取台灣銀行牌告匯率(XML 格式)資料。 在螢幕上顯示資料(匯率、幣別等資訊)。 自動將資料寫入 Google 雲端硬碟中的 myfile/rate9.csv。 """ # -*- coding: utf-8 -*- """ 這支程式檔名 bigdata0.ipynb 由 學號 xxxx000 羅老師 所撰寫 on 2025/05/04 功能為 能即時取得 台銀牌告匯率, 包括: 即時擷取台灣銀行牌告匯率(XML 格式)資料。 在螢幕上顯示資料(匯率、幣別等資訊)。 自動將資料寫入 Google 雲端硬碟中的 myfile/rate9.csv。 """ # 步驟 1:掛載 Google 雲端硬碟 from google.colab import drive drive.mount('/content/drive') # 步驟 2:主程式(擷取並儲存匯率) # 安裝 tabulate 套件並顯示資料對齊 !pip install tabulate # 匯入各 library(工具庫) 的模組或套件 import requests #發送 HTTP 請求,取得網頁資料或 API 資料 import pandas as pd #資料處理與分析工具庫 from datetime import datetime from bs4 import BeautifulSoup #解析 HTML/XML 的網頁爬蟲工具 import os #與作業系統互動(檔案、資料夾、環境變數等) import time from tabulate import tabulate #把表格資料格式化成漂亮的輸出(純文字表格) def fetch_and_save_rate(): url = "https://rate.bot.com.tw/xrt?Lang=zh-TW" response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") rows = soup.find("table", {"title": "牌告匯率"}).find_all("tr") data = [] now = datetime.now().strftime("%Y-%m-%d %H:%M:%S") for row in rows[1:]: cells = row.find_all("td") if len(cells) >= 6: currency_name = cells[0].text.strip().split()[0] cash_buy = cells[1].text.strip() cash_sell = cells[2].text.strip() spot_buy = cells[3].text.strip() spot_sell = cells[4].text.strip() data.append({ "時間": now, "幣別": currency_name, "現金買入": cash_buy, "現金賣出": cash_sell, "即期買入": spot_buy, "即期賣出": spot_sell }) df = pd.DataFrame(data) # 使用 tabulate 進行格式化顯示 print("\n" + tabulate(df, headers='keys', tablefmt='pretty', showindex=False)) # 儲存到 Google Drive drive_path = "/content/drive/My Drive/myfile" os.makedirs(drive_path, exist_ok=True) csv_file = os.path.join(drive_path, "rate9.csv") if not os.path.exists(csv_file): df.to_csv(csv_file, index=False, encoding="utf-8-sig") else: df.to_csv(csv_file, mode='a', header=False, index=False, encoding="utf-8-sig") print(f" {now} 資料已儲存至 {csv_file}") # 步驟 3:定時自動執行(每分鐘抓一次) # 執行 5 次,每分鐘一次(可依需要更改次數或間隔時間) for i in range(5): print(f"\n 第 {i+1} 次抓取:") fetch_and_save_rate() time.sleep(60) # 暫停 60 秒
|
|
中華科技大學數位化學習歷程 - 意見反應 | ![]() |