思路:
1、首先需要找到一個將股票信息存放在html上的股票網站
2、因爲每一個股票都是一個獨立的頁面,所以在抓取時,首先要了解每個股票網址的規律(網址最後結尾都是股票的代碼)
3、先要找到所有股票代碼,從東方財富網股票列表處來獲取所有股票的代碼
4、在一個個打開,獲取信息
代碼框架:
1、抓取頁面的函數
import re
from bs4 import BeautifulSoup
import requests as rs
import traceback as tb
#1、抓取函數
def getContent(url):
try:
r = rs.get(url)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
print('爬取失敗')
2、獲取存放着所有股票代碼的列表
def producer(stock_url,info_list):
html = getContent(stock_url) #獲取股票列表頁面
soup = BeautifulSoup(html,'html.parser')
a = soup.find_all('a') #找到所有a標籤全部存放到列表當中,此時a已經變成了一個列表
for i in a :
try:
href = i.attrs['href'] #尋找到所有href屬性的內容
info_list.append(re.findall(r"[s][hz]\d{6}",href)[0]) #利用正則表達式尋找符合內容的條件,因爲輸出的是一個列表所以用[0]可以將外面的框消除
except:
continue #因爲在找的過程中會出現各種錯誤,所以用try continue來保證程序繼續運行
3、存儲
def Save(inf_list,stock_url,fpath):
for i in info_list: #遍歷各個股票的代碼 一個一個打開網站
url = stock_url + i +'.html' #生成每支股票的url
html = getContent(url) #獲取頁面
try:
if html =='':
continue
soup = BeautifulSoup(html,'html.parser')
info_dict ={} #創建一個字典用來存放信息
a_list = soup.find('div',attrs={'class':'stock-bets'}) #找到div標籤下的屬性爲class 到stock-bets的內容
name = a_list.find_all(attrs = {'class':'bets-name'})[0] #找出名字
info_dict.update({'股票名稱',name.text.split()[0]}) #以字典的形式存放到字典當中
key_list = a_list.find_all('dv') #dv標籤下對應的是這隻股票所有鍵的名稱,生成該列表
value_list = a_list.find_all('dd')#所有值的名稱生成列表
for ee in range(len(key_list)):
key = key_list[i].text
value = value_list[i].text
info_dict[key]=value
with open(fpath,'w',encoding='utf-8') as f:
f.write(str(info_dict)+'\n')
except:
tb.print_exc() #打印錯誤的原因
continue
4、主函數運行
def main():
stock_list_url = 'http://quote.eastmoney.com/stock_list.html'
stock_url ='https://gupiao.baidu.com/stock/'
list = []
fpath = 'E:\\Text\\'
producer(stock_list_url,list)
Save(list,stock_url,fpath)
main()
總結:
1、BeautifulSoup()用來解析頁面,可以使得目標內容更好找(提高效率)
2、soup.find_all(‘標籤’) #把改標籤的內容存入一個list
3、soup.find_all(attrs = {‘屬性名’:‘屬性名’}) #可以找到目標屬性名
4、注意:要從不同網頁獲取信息,就要先獲取各個網頁之間的聯繫和規律
5、要經常的記得用異常處理來保證程序可以穩定的運行