輕鬆學習 Python |從基礎到應用,成為初級資料分析師 # 建置環境 ### 環境 課程採用 [Google Colab](https://colab.google ) ***需要*** Gmail帳號與Chrome 瀏覽器 ### 步驟: 1. 開啟 Google Cloud Driv  2. 若尚未安裝,則需新增連結Colaboratory app  3. 檢查環境 ``` import numpy print('numpy:', numpy.__version__) import pandas print('pandas:', pandas.__version__) import matplotlib print('matplotlib:', matplotlib.__version__) ``` # 網頁爬蟲 ### 常見模組 * requests/BeautifulSoup (靜態) * Selenium (動態) * yfinance (Yahoo Finance) | 特性 | requests + BeautifulSoup (靜態) | Selenium (動態) | yfinance (API 套件) | | :--- | :--- | :--- | :--- | | **運作原理** | 下載網頁原始碼 (HTML),直接取出文字。 | 開啟真實瀏覽器,等待畫面跑完,再截取看到的內容。 | 呼叫 Yahoo 的後台數據接口,直接下載整理好的表格。 | | **速度** | 🚀 **極快** (只傳文字) | 🐢 **慢** (需載入圖片/JS) | ⚡ **快** (直接拿數據) | | **開發難度** | ⭐⭐ (需懂 HTML/CSS) | ⭐⭐⭐ (需設定 Driver/Wait) | ⭐ (僅需 2 行程式碼) | | **最適合場景** | 抓取結構簡單、不會動的網頁 (如證交所歷史表格)。 | 抓取需要登入、一直滑動、圖表會跳動的網站 (如 Yahoo 首頁)。 | **金融分析首選**。獲取歷史股價、財報,做回測與模型。 | ### Requests/BeautifulSoup [Link](https://colab.research.google.com/drive/1vGRIkTPAetvv6WdAb7Zqv-mlT3KbMV2P) ``` import requests from bs4 import BeautifulSoup # 1. 設定目標網址 url = 'http://quotes.toscrape.com/' # 2. 抓取網頁 response = requests.get(url) # 3. 解析內容 soup = BeautifulSoup(response.text, 'html.parser') # 4. 測試抓取標題 title = soup.find('div', class_='header-box').find('a').text print(f"網頁標題抓取成功: {title}") # 5. 抓取前三句名言 quotes = soup.find_all('div', class_='quote', limit=3) print("\n--- 前三句名言 ---") for q in quotes: text = q.find('span', class_='text').text print(text) ``` ### yfinance (Yahoo Finance) [Link](https://colab.research.google.com/drive/1-NAk_GU9DrsRTUvy-nQrsxpr0-QdkZOF#scrollTo=tUEle8nFuEIZ) ``` import yfinance as yf def get_tsmc_latest_price(): # 1. 設定股票代碼 (台股需加 .TW) ticker = "2330.TW" stock = yf.Ticker(ticker) # 2. 獲取近期股價 (period='1d' 會自動抓取最近一個交易日的資料) # 即使今天是週日,它也會聰明地回傳週五的數據 data = stock.history(period="1d") if not data.empty: # 3. 提取數據 latest_date = data.index[-1].strftime('%Y-%m-%d') close_price = data['Close'].iloc[-1] # 嘗試獲取更多即時資訊 (若盤中會有 bid/ask,盤後通常看 regularMarketPrice) # 注意:.info有時請求會較慢或受限,若只要收盤價用 .history 最快 print(f"日期: {latest_date}") print(f"台積電 (2330) 收盤價: {close_price:.2f} 元") return close_price else: print("無法獲取資料,請檢查網路或代碼。") return None # 執行 price = get_tsmc_latest_price() ``` # Take Away 1.固定式網頁資訊使用requests/BeautifulSoup 2.動態式自動化多重動作使用Selenium 3.財經資訊爬蟲yfinance (Yahoo Finance)
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up