讀取股票資料儲存到本地MySQL資料庫(一)
阿新 • • 發佈:2019-01-02
主要有三個步驟:(1)從東方財富上爬蟲讀取到所有股票的codelist;(2)從鳳凰網的api獲取到某隻股票歷史上所有資料,開盤收盤價,成交量,成交金額,ma均線價格等資料;(3)通過pymysql將獲取到的資料儲存到本地。
第一個步驟的實現,從EAST_MONEY_URL = 'http://quote.eastmoney.com/stocklist.html'處獲取stocklist。主要使用
find_all()的查詢方式可以有多種,第一種按標籤方式查詢,上面的ul, div, li均是標籤;第二種按內容查詢,引數為text='xxx';第三種按正則表示式查詢。可以跟limit引數限定返回的list的長度,當limit=1時候也就是find()函數了。#encoding = uft-8 import requests from bs4 import BeautifulSoup import re class GetStockList(object): def get_html_text(self, url): try: response = requests.get(url) response.raise_for_status() response.encoding = 'utf-8' return response.text#html變數儲存讀取的網頁text except: return '' def get_stock_list(self, url): html = self.get_html_text(url) soup = BeautifulSoup(html, 'html.parser') a = soup.find_all('a') stock_list = [] for i in a: try: href = i.attrs['href'] stock_num = str(re.findall(r"[s][hz]\d{6}",href)[0]) if stock_num: stock_list.append(stock_num) except: continue return stock_list
查詢結果的list每個元素是bs4.element.ResultSet型別,可以繼續接find函式,也可以呼叫attrs屬性返回一個dict。
soup.find_all('a')會返回所有標籤為a的元素
In [44]: soup.find_all('a', limit=5) Out[44]: [<a href="http://finance.eastmoney.com/" target="_blank">�ƾ�</a>, <a href="http://finance.eastmoney.com/yaowen.html" target="_blank">Ҫ��</a>, <a href="http://stock.eastmoney.com/" target="_blank">��Ʊ</a>, <a href="http://stock.eastmoney.com/newstock.html" target="_blank">�¹�</a>, <a href="http://stock.eastmoney.com/gzqh.html" target="_blank">��ָ</a>] In [45]: soup.find_all('a', limit=5)[0].attrs Out[45]: {'href': 'http://finance.eastmoney.com/', 'target': '_blank'} In [46]: soup.find_all('a', limit=5)[0].attrs['href'] Out[46]: 'http://finance.eastmoney.com/'