自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Python爬蟲實(shí)戰(zhàn):股票數(shù)據(jù)定向爬蟲

開發(fā) 后端
股票信息靜態(tài)存在于html頁面中,非js代碼生成,沒有Robbts協(xié)議限制,打開網(wǎng)頁,查看源代碼,搜索網(wǎng)頁的股票價(jià)格數(shù)據(jù)是否存在于源代碼中。

功能簡(jiǎn)介

  • 目標(biāo): 獲取上交所和深交所所有股票的名稱和交易信息。
  • 輸出: 保存到文件中。
  • 技術(shù)路線: requests—bs4–re
  • 語言:python3.5

說明

  • 網(wǎng)站選擇原則: 股票信息靜態(tài)存在于html頁面中,非js代碼生成,沒有Robbts協(xié)議限制。
  • 選取方法: 打開網(wǎng)頁,查看源代碼,搜索網(wǎng)頁的股票價(jià)格數(shù)據(jù)是否存在于源代碼中。

如打開新浪股票網(wǎng)址:鏈接描述(http://finance.sina.com.cn/realstock/company/sz000877/nc.shtml),如下圖所示:

 

上圖中左邊為網(wǎng)頁的界面,顯示了天山股份的股票價(jià)格是13.06。右邊為該網(wǎng)頁的源代碼,在源代碼中查詢13.06發(fā)現(xiàn)沒有找到。所以判斷該網(wǎng)頁的數(shù)據(jù)使用js生成的,不適合本項(xiàng)目。因此換一個(gè)網(wǎng)頁。

再打開百度股票的網(wǎng)址:鏈接描述(https://gupiao.baidu.com/stock/sz300023.html),如下圖所示: 

 

從上圖中可以發(fā)現(xiàn)百度股票的數(shù)據(jù)是html代碼生成的,符合我們本項(xiàng)目的要求,所以在本項(xiàng)目中選擇百度股票的網(wǎng)址。

由于百度股票只有單個(gè)股票的信息,所以還需要當(dāng)前股票市場(chǎng)中所有股票的列表,在這里我們選擇東方財(cái)富網(wǎng),網(wǎng)址為:鏈接描述(http://quote.eastmoney.com/stocklist.html),界面如下圖所示:

 

原理分析

查看百度股票每只股票的網(wǎng)址:https://gupiao.baidu.com/stock/sz300023.html,可以發(fā)現(xiàn)網(wǎng)址中有一個(gè)編號(hào)300023正好是這只股票的編號(hào),sz表示的深圳交易所。因此我們構(gòu)造的程序結(jié)構(gòu)如下:

  • 步驟1: 從東方財(cái)富網(wǎng)獲取股票列表;
  • 步驟2: 逐一獲取股票代碼,并增加到百度股票的鏈接中,***對(duì)這些鏈接進(jìn)行逐個(gè)的訪問獲得股票的信息;
  • 步驟3: 將結(jié)果存儲(chǔ)到文件。

接著查看百度個(gè)股信息網(wǎng)頁的源代碼,發(fā)現(xiàn)每只股票的信息在html代碼中的存儲(chǔ)方式如下:

 

因此,在我們存儲(chǔ)每只股票的信息時(shí),可以參考上圖中html代碼的存儲(chǔ)方式。每一個(gè)信息源對(duì)應(yīng)一個(gè)信息值,即采用鍵值對(duì)的方式進(jìn)行存儲(chǔ)。在python中鍵值對(duì)的方式可以用字典類型。因此,在本項(xiàng)目中,使用字典來存儲(chǔ)每只股票的信息,然后再用字典把所有股票的信息記錄起來,***將字典中的數(shù)據(jù)輸出到文件中。

代碼編寫

首先是獲得html網(wǎng)頁數(shù)據(jù)的程序,在這里不多做介紹了,代碼如下:

  1. #獲得html文本 
  2.  
  3. def getHTMLText(url): 
  4.  
  5.     try: 
  6.  
  7.         r = requests.get(url) 
  8.  
  9.         r.raise_for_status() 
  10.  
  11.         r.encoding = r.apparent_encoding 
  12.  
  13.         return r.text 
  14.  
  15.     except
  16.  
  17.         return ""  

接下來是html代碼解析程序,在這里首先需要解析的是東方財(cái)富網(wǎng)頁面:鏈接描述(http://quote.eastmoney.com/stocklist.html),我們打開其源代碼,如下圖所示:

 

由上圖可以看到,a標(biāo)簽的href屬性中的網(wǎng)址鏈接里面有每只股票的對(duì)應(yīng)的號(hào)碼,因此我們只要把網(wǎng)址里面對(duì)應(yīng)股票的號(hào)碼解析出來即可。解析步驟如下:

***步,獲得一個(gè)頁面:

  1. html = getHTMLText(stockURL) 

第二步,解析頁面,找到所有的a標(biāo)簽:

  1. soup = BeautifulSoup(html, 'html.parser'
  2.  
  3. a = soup.find_all('a' 

第三步,對(duì)a標(biāo)簽中的每一個(gè)進(jìn)行遍歷來進(jìn)行相關(guān)的處理。處理過程如下:

1.找到a標(biāo)簽中的href屬性,并且判斷屬性中間的鏈接,把鏈接后面的數(shù)字取出來,在這里可以使用正則表達(dá)式來進(jìn)行匹配。由于深圳交易所的代碼以sz開頭,上海交易所的代碼以sh開頭,股票的數(shù)字有6位構(gòu)成,所以正則表達(dá)式可以寫為[s][hz]\d{6}。也就是說構(gòu)造一個(gè)正則表達(dá)式,在鏈接中去尋找滿足這個(gè)正則表達(dá)式的字符串,并把它提取出來。代碼如下:

  1. for i in a: 
  2.  
  3.     href = i.attrs['href'
  4.  
  5.     lst.append(re.findall(r"[s][hz]\d{6}", href)[0])  

2.由于在html中有很多的a標(biāo)簽,但是有些a標(biāo)簽中沒有href屬性,因此上述程序在運(yùn)行的時(shí)候出現(xiàn)異常,所有對(duì)上述的程序還要進(jìn)行try…except來對(duì)程序進(jìn)行異常處理,代碼如下:

  1. for i in a: 
  2.  
  3.     try: 
  4.  
  5.         href = i.attrs['href'
  6.  
  7.         lst.append(re.findall(r"[s][hz]\d{6}", href)[0]) 
  8.  
  9.     except
  10.  
  11.         continue  

從上面代碼可以看出,對(duì)于出現(xiàn)異常的情況我們使用了continue語句,直接讓其跳過,繼續(xù)執(zhí)行下面的語句。通過上面的程序我們就可以把東方財(cái)富網(wǎng)上股票的代碼信息全部保存下來了。

將上述的代碼封裝成一個(gè)函數(shù),對(duì)東方財(cái)富網(wǎng)頁面解析的完整代碼如下所示:

  1. def getStockList(lst, stockURL): 
  2.  
  3.     html = getHTMLText(stockURL) 
  4.  
  5.     soup = BeautifulSoup(html, 'html.parser'
  6.  
  7.     a = soup.find_all('a'
  8.  
  9.     for i in a: 
  10.  
  11.         try: 
  12.  
  13.             href = i.attrs['href'
  14.  
  15.             lst.append(re.findall(r"[s][hz]\d{6}", href)[0]) 
  16.  
  17.         except
  18.  
  19.             continue  

接下來是獲得百度股票網(wǎng)鏈接描述(https://gupiao.baidu.com/stock/sz300023.html)單只股票的信息。我們先查看該頁面的源代碼,如下圖所示:

 

股票的信息就存在上圖所示的html代碼中,因此我們需要對(duì)這段html代碼進(jìn)行解析。過程如下:

1.百度股票網(wǎng)的網(wǎng)址為:https://gupiao.baidu.com/stock/

一只股票信息的網(wǎng)址為:https://gupiao.baidu.com/stock/sz300023.html

所以只要百度股票網(wǎng)的網(wǎng)址+每只股票的代碼即可,而每只股票的代碼我們已經(jīng)有前面的程序getStockList從東方財(cái)富網(wǎng)解析出來了,因此對(duì)getStockList函數(shù)返回的列表進(jìn)行遍歷即可,代碼如下:

  1. for stock in lst: 
  2.  
  3. url = stockURL + stock + ".html"  

2.獲得網(wǎng)址后,就要訪問網(wǎng)頁獲得網(wǎng)頁的html代碼了,程序如下:

  1. html = getHTMLText(url) 

3.獲得了html代碼后就需要對(duì)html代碼進(jìn)行解析,由上圖我們可以看到單個(gè)股票的信息存放在標(biāo)簽為div,屬性為stock-bets的html代碼中,因此對(duì)其進(jìn)行解析:

  1. soup = BeautifulSoup(html, 'html.parser'
  2.  
  3. stockInfo = soup.find('div',attrs={'class':'stock-bets'}) 

4.我們又發(fā)現(xiàn)股票名稱在bets-name標(biāo)簽內(nèi),繼續(xù)解析,存入字典中:

  1. infoDict = {} 
  2.  
  3. name = stockInfo.find_all(attrs={'class':'bets-name'})[0] 
  4.  
  5. infoDict.update({'股票名稱'name.text.split()[0]})  

split()的意思是股票名稱空格后面的部分不需要了。

5.我們從html代碼中還可以觀察到股票的其他信息存放在dt和dd標(biāo)簽中,其中dt表示股票信息的鍵域,dd標(biāo)簽是值域。獲取全部的鍵和值:

  1. keyList = stockInfo.find_all('dt'
  2.  
  3. valueList = stockInfo.find_all('dd' 

并把獲得的鍵和值按鍵值對(duì)的方式村放入字典中:

  1. for i in range(len(keyList)): 
  2.  
  3. key = keyList[i].text 
  4.  
  5. val = valueList[i].text 
  6.  
  7. infoDict[key] = val  

6.***把字典中的數(shù)據(jù)存入外部文件中:

  1. with open(fpath, 'a', encoding='utf-8'as f: 
  2.  
  3. f.write( str(infoDict) + '\n' )  

將上述過程封裝成完成的函數(shù),代碼如下:

  1. def getStockInfo(lst, stockURL, fpath): 
  2.  
  3.     for stock in lst: 
  4.  
  5.         url = stockURL + stock + ".html" 
  6.  
  7.         html = getHTMLText(url) 
  8.  
  9.         try: 
  10.  
  11.             if html==""
  12.  
  13.                 continue 
  14.  
  15.             infoDict = {} 
  16.  
  17.             soup = BeautifulSoup(html, 'html.parser'
  18.  
  19.             stockInfo = soup.find('div',attrs={'class':'stock-bets'}) 
  20.  
  21.             name = stockInfo.find_all(attrs={'class':'bets-name'})[0] 
  22.  
  23.             infoDict.update({'股票名稱'name.text.split()[0]}) 
  24.  
  25.              
  26.  
  27.             keyList = stockInfo.find_all('dt'
  28.  
  29.             valueList = stockInfo.find_all('dd'
  30.  
  31.             for i in range(len(keyList)): 
  32.  
  33.                 key = keyList[i].text 
  34.  
  35.                 val = valueList[i].text 
  36.  
  37.                 infoDict[key] = val 
  38.  
  39.              
  40.  
  41.             with open(fpath, 'a', encoding='utf-8'as f: 
  42.  
  43.                 f.write( str(infoDict) + '\n' ) 
  44.  
  45.         except
  46.  
  47.             continue  

其中try…except用于異常處理。

接下來編寫主函數(shù),調(diào)用上述函數(shù)即可:

  1. def main(): 
  2.  
  3.     stock_list_url = 'http://quote.eastmoney.com/stocklist.html' 
  4.  
  5.     stock_info_url = 'https://gupiao.baidu.com/stock/' 
  6.  
  7.     output_file = 'D:/BaiduStockInfo.txt' 
  8.  
  9.     slist=[] 
  10.  
  11.     getStockList(slist, stock_list_url) 
  12.  
  13.     getStockInfo(slist, stock_info_url, output_file)  

項(xiàng)目完整程序

  1. # -*- coding: utf-8 -*- 
  2.  
  3.   
  4.  
  5. import requests 
  6.  
  7. from bs4 import BeautifulSoup 
  8.  
  9. import traceback 
  10.  
  11. import re 
  12.  
  13. def getHTMLText(url): 
  14.  
  15.     try: 
  16.  
  17.         r = requests.get(url) 
  18.  
  19.         r.raise_for_status() 
  20.  
  21.         r.encoding = r.apparent_encoding 
  22.  
  23.         return r.text 
  24.  
  25.     except
  26.  
  27.         return "" 
  28.  
  29. def getStockList(lst, stockURL): 
  30.  
  31.     html = getHTMLText(stockURL) 
  32.  
  33.     soup = BeautifulSoup(html, 'html.parser'
  34.  
  35.     a = soup.find_all('a'
  36.  
  37.     for i in a: 
  38.  
  39.         try: 
  40.  
  41.             href = i.attrs['href'
  42.  
  43.             lst.append(re.findall(r"[s][hz]\d{6}", href)[0]) 
  44.  
  45.         except
  46.  
  47.             continue 
  48.  
  49. def getStockInfo(lst, stockURL, fpath): 
  50.  
  51.     count = 0 
  52.  
  53.     for stock in lst: 
  54.  
  55.         url = stockURL + stock + ".html" 
  56.  
  57.         html = getHTMLText(url) 
  58.  
  59.         try: 
  60.  
  61.             if html==""
  62.  
  63.                 continue 
  64.  
  65.             infoDict = {} 
  66.  
  67.             soup = BeautifulSoup(html, 'html.parser'
  68.  
  69.             stockInfo = soup.find('div',attrs={'class':'stock-bets'}) 
  70.  
  71.             name = stockInfo.find_all(attrs={'class':'bets-name'})[0] 
  72.  
  73.             infoDict.update({'股票名稱'name.text.split()[0]}) 
  74.  
  75.              
  76.  
  77.             keyList = stockInfo.find_all('dt'
  78.  
  79.             valueList = stockInfo.find_all('dd'
  80.  
  81.             for i in range(len(keyList)): 
  82.  
  83.                 key = keyList[i].text 
  84.  
  85.                 val = valueList[i].text 
  86.  
  87.                 infoDict[key] = val 
  88.  
  89.              
  90.  
  91.             with open(fpath, 'a', encoding='utf-8'as f: 
  92.  
  93.                 f.write( str(infoDict) + '\n' ) 
  94.  
  95.                 count = count + 1 
  96.  
  97.                 print("\r當(dāng)前進(jìn)度: {:.2f}%".format(count*100/len(lst)),end=""
  98.  
  99.         except
  100.  
  101.             count = count + 1 
  102.  
  103.             print("\r當(dāng)前進(jìn)度: {:.2f}%".format(count*100/len(lst)),end=""
  104.  
  105.             continue 
  106.  
  107. def main(): 
  108.  
  109.     stock_list_url = 'http://quote.eastmoney.com/stocklist.html' 
  110.  
  111.     stock_info_url = 'https://gupiao.baidu.com/stock/' 
  112.  
  113.     output_file = 'D:/BaiduStockInfo.txt' 
  114.  
  115.     slist=[] 
  116.  
  117.     getStockList(slist, stock_list_url) 
  118.  
  119.     getStockInfo(slist, stock_info_url, output_file) 
  120.  
  121. main()  

上述代碼中的print語句用于打印爬取的進(jìn)度。執(zhí)行完上述代碼后在D盤會(huì)出現(xiàn)BaiduStockInfo.txt文件,里面存放了股票的信息。 

責(zé)任編輯:龐桂玉 來源: Python開發(fā)者
相關(guān)推薦

2022-09-19 11:41:39

數(shù)據(jù)分析Python數(shù)學(xué)模型

2017-06-19 15:32:39

Python爬蟲音頻數(shù)據(jù)

2017-08-09 15:27:33

python爬蟲開發(fā)工具

2024-11-27 06:31:02

2019-05-15 15:57:15

Python數(shù)據(jù)分析爬蟲

2018-07-02 14:12:26

Python爬蟲反爬技術(shù)

2023-01-03 08:20:15

2022-11-24 10:24:32

2017-06-14 15:20:43

Python爬蟲BeautifulSo

2020-10-19 19:25:32

Python爬蟲代碼

2024-05-31 12:31:54

C#爬蟲Python

2022-09-14 23:06:45

2017-12-20 09:35:25

Python爬蟲百度云資源

2021-03-04 11:37:13

Python服務(wù)端urllib

2022-03-22 09:00:00

數(shù)據(jù)庫SingleStor技術(shù)

2024-07-02 11:32:38

2021-08-23 11:15:20

Python機(jī)器學(xué)習(xí)bilibili

2021-08-21 14:30:58

機(jī)器學(xué)習(xí)bilibili股價(jià)

2024-06-07 08:56:43

HTTPPythonSelenium

2024-04-30 09:33:00

JavaScriptPythonexecjs
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)