股票數據定向爬蟲實例
目的:獲取上交所和深交所所有股票的名稱和交易信息
輸出:保存到文件中
技術路線:requests-bs4-re
候選數據網站的選擇
選取原則:股票信息靜態存於HTML頁面中,非js代碼生成,沒有Robots協議限制
選取方法:瀏覽器F12,源代碼查看
數據網站的確定
獲取股票列表
東方財富網:http://quote.eastmoney.com/stocklist.html
獲取個股信息
百度股票:http://gupiao.baidu.com/stock/
單個股票:http://gupiao.baidu.com/stock/sz002439.html
查看百度股票每只股票的網址:
https://gupiao.baidu.com/stock/sz300023.html
可以發現網址中有一個編號300023正好是這只股票的編號,sz表示的深圳交易所。因此我們構造的程序結構如下:
步驟1: 從東方財富網獲取股票列表;
步驟2: 逐一獲取股票代碼,並增加到百度股票的鏈接中,最后對這些鏈接進行逐個的訪問獲得股票的信息;
步驟3: 將結果存儲到文件。
查看百度個股信息網頁的源代碼,每只股票的信息在html代碼中的存儲方式如下
每一個信息源對應一個信息值,即采用鍵值對的方式進行存儲
在python中鍵值對的方式可以用字典類型
因此,在本項目中,使用字典來存儲每只股票的信息,然后再用字典把所有股票的信息記錄起來,最后將字典中的數據輸出到文件中
代碼
1 import requests 2 from bs4 import BeautifulSoup 3 import traceback 4 import re 5 import bs4 6 7 def getHTMLText(url,code='utf-8'): #使用code提高解析效率 8 try: 9 r = requests.get(url) 10 r.raise_for_status() 11 r.encoding = code 12 return r.text 13 except: 14 return '爬取失敗' 15 16 def getStockList(lst,stockURL): 17 html = getHTMLText(stockURL,'GB2312') 18 soup = BeautifulSoup(html,'html.parser') 19 a = soup.find_all('a') 20 for i in a : 21 try: 22 href = i.attrs['href'] 23 #以s開頭,中間是h或z,后面再接六位數字 24 lst.append(re.findall(r'[s][hz]\d{6}',href)[0]) 25 except: 26 continue 27 28 def getStockInfo(lst,stockURL,fpath): 29 count = 0 30 for stock in lst: 31 url = stockURL + stock +'.html' 32 html = getHTMLText(url) 33 try: 34 if html == "": 35 continue 36 infoDict = {} 37 soup = BeautifulSoup(html,'html.parser') 38 stockInfo = soup.find('div',attrs={'class':'stock-bets'} 39 if isinstance(stockInfo,bs4.element.Tag): 40 name = stockInfo.find_all(attrs={'class':'bets-name'})[0] 41 infoDict.update({'股票名稱':name.text.split()[0]}) 42 keyList = stockInfo.find_all('dt') 43 valueList = stockInfo.find_all('dd') 44 for i in range(len(keyList)): 45 key = keyList[i].text 46 val = valueList[i].text 47 infoDict[key] = val 48 with open(fpath,'a',encoding='utf-8') as f: 49 f.write(str(infoDict) + '\n') 50 count += 1 51 print('\r當前速度:{:.2f}%'.format(count*100/len(lst)),end='') 52 #打印爬取進度 53 except: 54 print('\r當前速度:{:.2f}%'.format(count*100/len(lst)),end='') 55 traceback.print_exc() 56 continue 57 58 def main(): 59 stock_list_url = 'http://quote.eastmoney.com/stocklist.html' 60 stock_info_url = 'http://gupiao.baidu.com/stock/' 61 output_file = 'C:/Users/Administrator/Desktop/Python網絡爬蟲與信息提取/BaiduStockInfo.txt' 62 slist = [] 63 getStockList(slist,stock_list_url) 64 getStockInfo(slist,stock_info_url,output_file) 65
66 main()
運行結果