2018年12月9日 星期日

Python_讀取股票歷年經營績效_以遠東新1402為例_01_使用pandas與BeautifulSoup取得網頁資料

因為最近想要用一些統計方法去評估股票,所以要整理一些資訊到自己的PC分析,在思考要怎麼取得股票的資訊,會的程式語言列了一下: C#要開VS好浪費資源 R處理資料好像不方便 Python好像還不賴,於是興致一來花了一些時間來研究。 結果...哇....短短的幾行Code效果令人驚艷。 趕快紀錄一下,以後用來紀念
import requests
from bs4 import BeautifulSoup
import pandas as pd 

url = 'https://goodinfo.tw/StockInfo/StockBzPerformance.asp?STOCK_ID=1402'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'}
r = requests.get(url, headers = headers)
r.encoding = 'utf-8'
soup = BeautifulSoup(r.text, 'html.parser')
rows = soup.find('div', {"id": "divFinDetail"}).find('table', {"class": "solid_1_padding_4_0_tbl"})
dfs = pd.read_html(str(rows))
print (dfs[0])
dfs[0].to_html("1402.html",index=False)
執行結果

沒有留言:

張貼留言