陳惠妤的學習歷程檔案 - 111-1大數據分析 - 8.超簡單用python抓取每月營收
 

夜四技企資三甲
1101AD010
陳惠妤


歷程檔案 Portfolio

    8.超簡單用python抓取每月營收

    程式碼:
    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


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




    資料來源:https://www.finlab.tw/%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/
    程式實作:https://colab.research.google.com/drive/13BTrubo-gyap6pCdQBdmEVFspMy7sBoU?usp=sharing

    全部共 0則留言
    登入帳號密碼代表遵守學術網路規範


    文章分類 Labels


    最新文章 Top10

    中華科技大學數位化學習歷程 - 意見反應