# 超簡單用 Python 抓取每月營收：30 行爬蟲下載全台股月營收

台股研究 2020年7月22日 約 1 分鐘閱讀

30 行 Python 爬蟲就能從 TWSE 公開資訊觀測站下載全台股每月營收，支援民國與西元年份切換，附完整 monthly\_report 函式與 BIG5 編碼處理、偽瀏覽器 header 與停頓設定，是用 Python 打造投資自動化系統與看盤軟體的第一步。

不用買昂貴財經軟體，30 行 Python 就能爬下全台股每月營收。

今天承接上次的超簡單 python 系列，教大家如何得到每家企業每個月的營收。這個系列的最終目的就是讓大家可以創造自己的投資自動化程式，甚至擁有自己的看盤軟體。

真的不要把[程式交易](https://finlab.finance/tools/program-trading)想像的很難，感覺爬 2000 多支股票，並整理資料，好像是一件很累很痛苦的是情，但真的只需要 30 行，你可能會覺得這些代碼真的太短了，但真的就是這麼短，然而這必須建立在 python 或是 R，這些 package 豐富的腳本語言才有可能辦到，這兩個語言都不錯，但我比較喜歡寫 python 就是了 XD，因為 python 還可以做很多酷炫的事情，例如寫 server，或是一些自動化工具，然而 R 好像沒有這麼多功能？

那我們就來爬取吧！首先先決定要爬哪個網頁，我選擇的是 [TWSE 官方網頁](http://mops.twse.com.tw/nas/t21/sii/t21sc03_103_2_0.html) 它的網址是 <http://mops.twse.com.tw/nas/t21/sii/t21sc03_103_2_0.html>

各位有看到 103 這個數字嗎？其實這個就是年份，而緊接在後面的 “2” 就是月份，所以只要改動這兩個值，我們就可以下載不同年月的歷史資訊：

月爬蟲

顯示程式碼

```
import pandas as pd
import requests
from io import StringIO
import time
def monthly_report(year, month):
    
    # 假如是西元，轉成民國
    if year > 1990:
        year -= 1911
    
    url = 'https://mops.twse.com.tw/nas/t21/sii/t21sc03_'+str(year)+'_'+str(month)+'_0.html'
    if year <= 98:
        url = 'https://mops.twse.com.tw/nas/t21/sii/t21sc03_'+str(year)+'_'+str(month)+'.html'
    
    # 偽瀏覽器
    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
    
    # 下載該年月的網站，並用pandas轉換成 dataframe
    r = requests.get(url, headers=headers)
    r.encoding = 'big5'
 
    dfs = pd.read_html(StringIO(r.text), encoding='big-5')
 
    df = pd.concat([df for df in dfs if df.shape[1] <= 11 and df.shape[1] > 5])
    
    if 'levels' in dir(df.columns):
        df.columns = df.columns.get_level_values(1)
    else:
        df = df[list(range(0,10))]
        column_index = df.index[(df[0] == '公司代號')][0]
        df.columns = df.iloc[column_index]
    
    df['當月營收'] = pd.to_numeric(df['當月營收'], 'coerce')
    df = df[~df['當月營收'].isnull()]
    df = df[df['公司代號'] != '合計']
    
    # 偽停頓
    time.sleep(5)
 
    return df
```

依本文重跑

## 執行這個策略

複製提示詞，讓 AI 依照上方證據的資料、條件與風險檢查重跑一次。

告訴你的AI：

幫我設定 FinLab，重現這篇文章，請讀：https\://finlab.finance/setup?relatedUrl=/blog/python-fetch-monthly-revenue

[免安裝，開啟 FinLab Studio](https://studio.finlab.finance/chat?lang=zh\&research_context=%7B%22v%22%3A1%2C%22source_url%22%3A%22https%3A%2F%2Ffinlab.finance%2Fblog%2Fpython-fetch-monthly-revenue%22%7D)

以上這段程式碼就是一個 function 可以在其它地方隨時呼叫，code 真的超短，但這樣就夠了！

接下來我們隨意讀取任意年月份（可以用民國或是西元都支援）：

月爬蟲

顯示程式碼

```
# 民國100年1月
monthly_report(100,1)
 
# 西元2011年1月
monthly_report(2011,1)
```

就會跑出以下的表格：

[![Python 爬蟲下載台股每月營收後輸出的 pandas dataframe 表格，包含公司代號與當月營收](https://r2.finlab.finance/blog/%E8%B6%85%E7%B0%A1%E5%96%AE%E7%94%A8python%E6%8A%93%E5%8F%96%E6%AF%8F%E6%9C%88%E7%87%9F%E6%94%B6/table.png)](https://r2.finlab.finance/blog/%E8%B6%85%E7%B0%A1%E5%96%AE%E7%94%A8python%E6%8A%93%E5%8F%96%E6%AF%8F%E6%9C%88%E7%87%9F%E6%94%B6/table.png)

其實寫程式真的好簡單 XDD，坊間財經軟體都好貴，不就是幾行 code 而已，是不是！ 目前已經交完 日、月 的資料爬取了，下一次就是一季囉！

當然還有各式各樣可以爬的東西，有時間再跟大家介紹～

***

## 延伸閱讀

* [月營收這樣看！三種月營收選股法 Python 實作](https://finlab.finance/blog/python-monthly-revenue-three-methods)
* [Python 財報月報股價爬蟲：台股資料庫解決之道](https://finlab.finance/blog/python-taiwan-stock-database)
* [選股方法總覽：四大面向完整教學](https://finlab.finance/tools/stock-selection)

**投資警語：本文僅供教學參考，不構成投資建議。過去績效不代表未來表現，投資有風險。**

![韓承佑](https://finlab.finance/people/cheng-yu-han-avatar.jpg)

韓承佑

創辦人 & 量化研究員

韓承佑是 FinLab 創辦人，也是開源 Python 量化套件 finlab 的作者，長年投入台股與美股的量化策略研究、回測與教學。

[在 GitHub 上追蹤 →](https://github.com/koreal6803) [在 LinkedIn 上連結 →](https://www.linkedin.com/in/cheng-yu-han/)

FinLab AI

### 想建立自己的策略？

用自然語言描述你的選股想法，AI 自動驗證、回測、給你答案

[免費開始](https://finlab.finance/#get-started)

## 更多價值與基本面研究

[查看全部](https://finlab.finance/blog/category/value)

* [![現金股利調高選股：加進月營收動能，7 年年化 59.9%、夏普 1.83](https://r2.finlab.finance/blog/cash-dividend-increase-stock-selection/chart_equity.png) 現金股利調高選股：加進月營收動能，7 年年化 59.9%、夏普 1.83 年化報酬 59.9% · 台股](https://finlab.finance/blog/cash-dividend-increase-stock-selection)
* [![營收創新高選股：月營收動能優先買營收創 12 個月新高，年化 52.4%、夏普 1.62](https://r2.finlab.finance/blog/revenue-new-high-stock-selection/chart_equity.png) 營收創新高選股：月營收動能優先買營收創 12 個月新高，年化 52.4%、夏普 1.62 年化報酬 52.4% · 台股](https://finlab.finance/blog/revenue-new-high-stock-selection)
* [![月營收動能選股：台股 11 年回測年化 50%，夏普 1.46（附程式碼）](https://r2.finlab.finance/blog/monthly-revenue-momentum/chart_summary.png) 月營收動能選股：台股 11 年回測年化 50%，夏普 1.46（附程式碼） 年化報酬 50.0% · 台股](https://finlab.finance/blog/monthly-revenue-momentum)
* [![財報選股 3 指標回測：2020 年起年化 45.6%，近三年輸 0050](https://r2.finlab.finance/blog/fundamental-3-indicators/image-4-1024x938.png) 財報選股 3 指標回測：2020 年起年化 45.6%，近三年輸 0050 年化報酬 45.6% · 台股](https://finlab.finance/blog/fundamental-3-indicators)

來源：https://finlab.finance/blog/python-fetch-monthly-revenue｜資料日期：依上文各表格與段落標示｜頁面更新：2026-11-25
