logo
Loading...

【學員提問補充】(1) 爬蟲套件結合 pandas.read_html 使用 - 【教材專區】Python網路爬蟲工作坊|金融應用篇 - Cupoy

若遇到要爬取的網頁內容是 <table></table> 節點內的資料 可使用 pandas.read_html 解析 html 字串直接輸出表格。 實例如下: # 載入套件 import pan...

若遇到要爬取的網頁內容是
節點內的資料 可使用 pandas.read_html 解析 html 字串直接輸出表格。 實例如下: # 載入套件 import pandas as pd import requests # 變數設置 headers = { "User-Agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Mobile Safari/537.36", "Content-Type": "application/x-www-form-urlencoded" } url = 'https://mops.twse.com.tw/mops/web/ajax_stapap1' stock_id = 1102 year = 110 month = 11 payload = { 'encodeURIComponent': '1', 'step': '1', 'firstin': '1', 'off': '1', 'keyword4': '', 'code1': '', 'TYPEK2': '', 'checkbtn': '', 'queryName': 'co_id', 'inpuType': 'co_id', 'TYPEK': 'all', 'isnew': 'false', 'co_id': str(stock_id), 'year': str(year), 'month': str(month).zfill(2) } # 發送 Requests res = requests.post(url, data=payload, headers=headers).content # 解析網頁 soup = BeautifulSoup(res, 'html.parser') # 解析 html 物件轉為 DataFrame table = soup.find('table', {'class': 'hasBorder'}) df = pd.read_html(str(table))[0] # read_html 會將 html 物件內所有 ###draft_code_symbol_lessthen###table> 都轉成 DataFrame,因此輸出會是 list 形式 df.head(10) 輸出結果: 再經過一些 DataFrame 的處理則可以變成我們預期的樣子 # 將第一列、第二列欄位合併 merge_headers = (df.iloc[0, -3:] + "-" + df.iloc[1, -3:]).values.tolist() df.columns = df.iloc[0, :-3].values.tolist() + merge_headers # 排除無意義列、重新 index (避免後面的處理發生問題) df = df.iloc[2:, :].reset_index(drop=True) df = df[df['職稱']!="職稱"].reset_index(drop=True) df.head(10) 輸出結果: