How to scrape Yahoo Finance stock data with Python

This time, we are going to learn the hands-on ability to scrape Yahoo financial data. Set-up python environment. Yahoo Finance page. For example, Alphabet Inc. (GOOG). Scrape & parse the page. The page we will be scrape. In the “network” page, we can’t find the json data. You can get all the data from the page source in script. View page source - script - root.App.main from bs4 import BeautifulSoup import re import json import requests response = requests.get("https://finance.yahoo.com/quote/GOOG?p=GOOG&.tsrc=fin-srch") soup = BeautifulSoup(response.text, "html.parser") ## print(soup.prettify()) script = soup.find('script', text=re.compile('root.App.main')).text data = json.loads(re.search("root.App.main\\s+=\\s+({.*})", script).group(1)) stores = data["context"]["dispatcher"]["stores"] print(stores) Response data ...

2021-09-02 · 2 min · 358 words · KbWen

python 爬取及時股價

如何取得即時的股價資訊 進入證交所提供的基本市況報導網站,右上方輸入股票代號,以2330為例。 看到當日的最高、最低、成交價量和最佳五檔等等。 此時在網頁上右鍵點選Inspect打開DevTools切換到Network欄位並觀察 爬蟲頁面 發現會一直get某個網址,名稱開頭是getStockInfo,應該就是我們要的資訊了。 import requests url = "https://mis.twse.com.tw/stock/api/getStockInfo.jsp?ex_ch=tse_2330.tw" res = requests.get(url) res.json() 得到一個排列整齊的json {'queryTime': {'stockInfoItem': 4329, 'sessionKey': 'tse_2330.tw_20200908|', 'sessionStr': 'UserSession', 'sysDate': '20200908', 'sessionFromTime': -1, 'stockInfo': 2084673, 'showChart': False, 'sessionLatestTime': -1, 'sysTime': '12:05:35'}, 'referer': '', 'rtmessage': 'OK', 'exKey': 'if_tse_2330.tw_zh-tw.null', 'msgArray': [{'n': '台積電', 'g': '281_174_260_166_385_', 'u': '468.5000', 'mt': '060262', 'o': '428.0000', 'ps': '593', 'tk0': '2330.tw_tse_20200908_B_9998775018', 'a': '430.5000_431.0000_431.5000_432.0000_432.5000_', 'tlong': '1599537930000', 't': '12:05:30', 'it': '12', 'ch': '2330.tw', 'b': '430.0000_429.5000_429.0000_428.5000_428.0000_', 'f': '143_239_162_400_391_', 'w': '383.5000', 'pz': '428.0000', 'l': '427.5000', 'c': '2330', 'v': '16843', 'd': '20200908', 'tv': '-', 'tk1': '2330.tw_tse_20200908_B_9998774678', 'ts': '0', 'nf': '台灣積體電路製造股份有限公司', 'y': '426.0000', 'p': '0', 'i': '24', 'ip': '0', 'z': '-', 's': '-', 'h': '433.0000', 'ex': 'tse'}], 'userDelay': 5000, 'rtcode': '0000', 'cachedAlive': 7891} 在爬取網址時,不要亂刪後面的query parameters,除非你確認過差別是甚麼。 如果不能爬,Request Headers就是你要注意的地方。 理解和實驗精神 比較一下哪個是我們要的資訊。 u: 漲停 v: 跌停 z: 當盤成交價,有時候會沒有 s: 當盤成交量,有時候也會沒有;整理數據時可以根據z和s的有無來過濾。 a: 賣出最佳五檔價 f: 賣出最佳五檔量 l: 當日最低 h: 當日最高 ….. 其他參數可以再自行看看,如果今天你想專注於某支股票的狀態;例如盤中是否有大量,那麼只需重複get url取得json做判斷;若想要得到更多支當下股票資訊以及儲存就需要用到dataframe。下面給個盤中抓取多隻股價的方式。 ...

2020-09-08 · 2 min · 303 words · KbWen