說明:所有內容均作爲學習用途
一.功能描述
1.獲取上交所所有股票的名稱和交易信息;
2.保存到文件中
3.技術路線 requests-bs4-re
二.候選網站數據選擇
1.股票信息靜態存在於HTML頁面中,非js代碼生成;無robots協議限制;
2.選取方法:源代碼查看,例如 本案例選取的 同花順,右鍵網頁查看源代碼,複製關鍵詞,如 中國平安,可在源代碼中找到,此爲代碼寫在HTML中;
候選網站:同花順,作爲獲取滬交所股票代碼編號;集思錄獲取具體的股票信息。
目標獲取的信息如下:
三.程序結構的設計
1. 從東方財富網獲取股票列表
2. 根據股票列表逐個到百度股票獲取個股信息
3. 將結果存儲到文件
源代碼分析:只要獲取到 a 標籤,然後獲取到其中鏈接的股票代碼即可(使用正則表達式\d{6}
)
這一部代碼:
def getStockList(lst,stockURL):
# 在同花順網站獲取股票編碼
html = getHTMLText(stockURL)
soup = BeautifulSoup(html,'lxml')
a = soup.find_all('a')
for i in a:
try:
href = i.attrs['href']
if re.findall(r'(?<=/)\d{6}(?=/)',href)[0] not in lst:
lst.append(re.findall(r'(?<=/)\d{6}(?=/)',href)[0])
except:
continue
print(lst) # 股票編碼
接着根據獲取的目標股票代碼,https://www.jisilu.cn/data/stock/601318,其最後的數字爲股票代碼;
獲取響應的html代碼片段
def getStockInfo(lst,stockURL,fpath):
for stock in lst:
# 根據在同花順網站獲取的股票編碼+集思錄url獲取某個股票的具體信息
url = stockURL + stock;
html = getHTMLText(url)
try:
if html=="":
continue
infoDict = {}
soup = BeautifulSoup(html,'lxml')
divList = soup.find('div',attrs={'class':'grid data_content'})
count = 0
mystr = ""
for div in divList:
# print(div)
mystr = mystr + str(div)
count += 1
if count >= 8:
break
# 這一部分就是僅獲取圖片中的那一部分的數據,爲什麼是8?我是一點一點數字放大打印出來的
mystr = mystr.replace('<td> </td>', '')# 將代碼中的空格替換掉
mystr = mystr.replace('<td style="width: 20px;"> </td>','') # 同上
myhtml = BeautifulSoup(mystr,'html.parser')
name = myhtml.find_all('li',attrs={'class':'active'})[0]
infoDict.update({'股票名稱':name.text.split()})
keylist = myhtml.find_all('td')
keykeylist = []
for key in keylist:
strkey = str(key)
strkey = strkey.replace('\n','')
match = re.search(r'(?<=\>).*?(?=\<span)',strkey) or re.search(r'(?<=\>).*?(?=\<sup)',strkey)
# 將<td title="5年平均股息率:-">股息率<sup>TTM</sup><span class="dc">15.066%</span>和
# <td style="width: 150px;">現價 <span class="dc">5.310</span></td>
# 將關鍵字 現價 和 股息率 提取出來
if match:
keykeylist.append(match.group(0).replace(' ','').replace('<sup>TTM</sup>',''))
# 將關鍵字中的空格換行,其他沒有信息替換掉
valuelist = myhtml.find_all('span',attrs={'class':'dc'})
for i in range(len(valuelist)):
key = keykeylist[i]
val = valuelist[i].text
infoDict[key] = val
#print(infoDict)
with open(fpath,'a',encoding='utf-8') as f:
f.write(str(infoDict)+'\n')
except:
traceback.print_exc()
continue
獲取html文本的代碼
def getHTMLText(url):
try:
headers = {'User-Agent': 'Your-Agent',
'Cookie':'Your-cookie'}
r = requests.get(url,headers=headers)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return ""
其中header中的數據來源和原因可見 鏈接
最後代碼的主體部分
import requests
from bs4 import BeautifulSoup
import traceback
import re
def main():
stock_list_url_hg = "http://data.10jqka.com.cn/hgt/hgtb/" #滬股
stock_info_url = "https://www.jisilu.cn/data/stock/"
output_file = "D:\\self_taught\\python\\WebCrawler\\BaiduStockInfo.txt"
slist = []
getStockList(slist,stock_list_url_hg)
getStockInfo(slist,stock_info_url,output_file)
main()
運行結果:
我是打印出來,也可在文本文件中查看。