從股票列表網頁獲取股票代碼
根據股票代碼去股票詳情頁面獲取股票詳細信息
1、 股票列表頁面
鳳凰網財經—股票信息
http://app.finance.ifeng.com/list/stock.php?t=ha&f=chg_pct&o=desc&p=1
2、 股票詳細信息
老虎社區—股票詳情
https://www.laohu8.com/stock/600210
實現一:requests—bs4—re
股票數據定向爬取思路
1、 查看網站robots協議,查看網站是否可以爬取
2、 查看網頁源代碼,查看網頁信息是否可以直接爬取
3、 爬取網頁信息
4、 解析網頁,獲取頁面信息
在HTML頁面中
1) 對於非常有特征的數據,可以直接用正則表達式搜索到
2) 信息存在的區域相對固定,則用BeautifulSoup定位標簽位置,再用正則表達式獲取
5、 將獲取的信息儲存到文件中
優化代碼
1、提高爬蟲速度
直接賦值編碼
2、提高程序運行體驗(運行時間較長的程序)
增加動態精度顯示
import requests
from bs4 import BeautifulSoup
import re
import traceback
def getHTMLText(url, code='utf-8'):
try:
r = requests.get(url)
r.raise_for_status()
r.encoding = code
return r.text
except:
print('爬取失敗')
def getStockList(lst, stockURL):
html = getHTMLText(stockURL, 'GB2312')
soup = BeautifulSoup(html, 'html.parser')
a = soup.find_all('a')
for i in a:
try:
href = i.attrs['href']
lst.append(re.findall(r"[s][hz]\d{6}", href)[0]) ## 匹配 a 標簽中 href 屬性以 s 開頭,中間是 h 或 z ,最后是6位數字
except:
continue
def getStockInfo(lst, stockURL, fpath):
## 去掉列表里的重復選項--將列表轉換為集合再轉換為列表
lst = list(set(lst))
count = 0
for stock in lst:
url = stockURL + stock[-6:]
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':'name'})[0]
price = stockInfo.find_all(attrs={'class': 'latest'})[0]
infoDict.update({'股票名稱':name.text.split()[0], '最新行情':price.text.split()[0]})
keyList = stockInfo.find_all('dt')
valueList = stockInfo.find_all('dd')
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='')
except:
traceback.print_exc() ## 獲得發生異常的錯誤信息
continue
def main():
stock_list_url = 'http://app.finance.ifeng.com/list/stock.php?t=ha'
stock_info_url = 'https://www.laohu8.com/stock/'
output_file = 'C:\\try\\StockInfo.txt'
slist = []
getStockList(slist, stock_list_url)
getStockInfo(slist, stock_info_url, output_file)
main()

實現二:Scrapy庫
