自學python之爬蟲3股票數據爬蟲


目標:獲取股票上交所和深交所所有股票的名稱和交易信息,保存在文件中

使用到的技術:requests+bs4+re

網站的選擇(選取原則:股票信息靜態存在HTML頁面,非js代碼生成沒喲robot協議限制)

  1. 獲取股票列表:http://quote.eastmoney.com/stocklist.html (因為東方財富網站的有全部股票信息的列表,百度股票網站只要個股信息)

  2. 獲取個股信息:

    百度股票:https://gupiao.baidu.com/stock/

    單個股票:https://gupiao.baidu.com/stock/sz002939.html

程序的設計結構:

  步驟1:從東方財富獲取股票列表

  步驟2:根據股票列表逐個到百度股票獲取個股信息

  步驟3:將結果存儲到文件

【步驟1】

通過發送請求獲取到東方財富網站股票列表信息,查看頁面源代碼,如下:

發現股票代碼存儲在<a>的href屬性中,且上交和深交的股票代碼前分別為“sh”和"sz",接下來可以利用這個規律進行解析和匹配。

首先使用BeautifulSoup4獲取所有<a>:

  soup = BeautifulSoup(html, 'html.parser')
  a = soup.find_all('a')

然后配合正則表達式提取的股票代碼,並存儲在lst列表中:

for i in a:
  try:
    href = i.attrs['href']
    lst.append(re.findall(r"[s][hz]\d{6}", href)[0])
  except:
    continue

此時列表 lst = ['sh201000' , 'sh201001' , 'sh201002' ...]

【步驟2】

接下來根據獲取的股票代碼列表,逐個在百度股票獲取個股信息。

百度股票個股信息的url:https://gupiao.baidu.com/stock/sz002939.html

因此,先進行url的拼接,然后發送請求獲取頁面

  for stock in lst:  

    url = 'https://gupiao.baidu.com/stock/' + stock + ".html"

    html = getHTMLText(url)

然后進行頁面解析,查看源代碼

發現所有的股票信息都存在的<dt><dd>中,然后使用BeautifulSoup進行一步一步的解析

soup = BeautifulSoup(html, 'html.parser')

stockInfo = soup.find('div',attrs={'class':'stock-bets'})

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

else:
  print('stockInfo is null')
  break
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

此時,infoDict = {"成交量":"31.07萬手" , "最高":"9.89", "漲停":"10.86" ...}

【步驟3】

最后,把結果輸出到文件中:

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

 

完整代碼如下:

#CrawBaiduStocksA.py
import requests
from bs4 import BeautifulSoup
import traceback
import re
 
#獲取頁面的公共方法
def getHTMLText(url):
    try:
        r = requests.get(url)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return "get fail"

#獲取股票代碼列表
def getStockList(lst, stockURL):
    html = getHTMLText(stockURL)
    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])           
        except:
            continue
 
#獲取個股信息並輸出到文件中
def getStockInfo(lst, stockURL, fpath):
    for stock in lst:
        url = stockURL + stock + ".html"
        html = getHTMLText(url)
        try:
            if html=="":
                continue
            infoDict = {}
            soup = BeautifulSoup(html, 'html.parser')
            stockInfo = soup.find('div',attrs={'class':'stock-bets'})
            if stockInfo:
                name = stockInfo.find_all(attrs={'class':'bets-name'})[0]
                infoDict.update({'股票名稱': name.text.split()[0]})
            else:
                print('stockInfo is null')
                break
            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' )
        except:
            traceback.print_exc()
            continue
 
def main():
    stock_list_url = 'http://quote.eastmoney.com/stocklist.html' #東放財富股票列表
    stock_info_url = 'https://gupiao.baidu.com/stock/' #百度股票信息
    output_file = 'D:/BaiduStockInfo.txt' #結果存儲的文件
    slist=[]
    getStockList(slist, stock_list_url)
    getStockInfo(slist, stock_info_url, output_file)
 
main()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM