在上一篇博客中,我們介紹了爬高校排名的爬蟲程序,本篇博客我們將介紹爬股票數據的程序。
程序來源:中國大學MOOC網《網絡爬蟲與信息提取課程》。
程序目的:獲取上交所和深交所的部分股票信息,輸出到文件。
讀懂以下程序需提前了解requests庫、BeautifulSoup庫和re庫,在《網絡爬蟲與信息提取課程》有提供相關知識。
import requests from bs4 import BeautifulSoup import re def getHTMLText(url, code="utf-8"): try: r = requests.get(url) r.raise_for_status() r.encoding = code # 直接指定用utf-8解碼 return r.text except: return "" def getStockList(lst, stockURL): html = getHTMLText(stockURL, "GB2312") # 東方財富網用的是GB2312編碼 soup = BeautifulSoup(html, 'html.parser') a = soup.find_all('a')[:200] # 股票代碼在a標簽中的href屬性中。我們只取前100個a標簽 for i in a: try: href = i.attrs['href'] lst.append(re.findall(r"\d{6}", href)[0]) except: continue def getStockInfo(lst, stockURL, fpath): count = 0 for stock in lst: url = stockURL + stock # 每只股票的信息的鏈接 html = getHTMLText(url) try: if html == "": continue infoDict = {} # 每只股票的信息都存在字典中 soup = BeautifulSoup(html, 'html.parser') stockInfo = soup.find('div', attrs={'class': 'stock-info'}) name = stockInfo.find_all(attrs={'class': 'stock-name'})[0] infoDict.update({'股票名稱': name.text.split()[0]}) # .text可以取出標簽中的字符串 keyList = stockInfo.find_all('dt')[:4] # 只取股票的前4個信息 valueList = stockInfo.find_all('dd')[:4] for i in range(len(keyList)): key = keyList[i].text val = valueList[i].text infoDict[key] = val with open(fpath, 'a', encoding='utf-8') as f: f.write(str(infoDict) + '\n') count = count + 1 print("\r當前進度: {:.2f}%".format(count * 100 / len(lst)), end="") # \r表示返回到當前行的起始位置,打印的內容會覆蓋之前打印的內容 # 每次print之后,會自動換行。end用來取消自動換行。 except: count = count + 1 print("\r當前進度: {:.2f}%".format(count * 100 / len(lst)), end="") continue def main(): stock_list_url = 'https://quote.eastmoney.com/stock_list.html' # 從東方財富網獲取每只股票的代碼 stock_info_url = 'https://www.laohu8.com/stock/' # 從老虎社區網站獲取每只股票的信息 output_file = '/Users/wangpeng/Desktop/BaiduStockInfo.txt' slist = [] getStockList(slist, stock_list_url) getStockInfo(slist, stock_info_url, output_file) main()
文件結果: