Python程序設計思維練習---股票數(shù)據(jù)定向爬蟲

  • 本次練習是一個定向爬蟲,爬取股票的相關(guān)數(shù)據(jù),用到beautifulsoup,re,requests等庫。
  • 爬前分析:先分析比較不同網(wǎng)站提供的股票數(shù)據(jù),在這里比較的是新浪股票百度股票。因為百度股票的相關(guān)數(shù)據(jù)直接在html頁面中爬取相對方便,而新浪股票的數(shù)據(jù)是通過js來傳遞的,獲取比較麻煩,所以選擇百度股票作為數(shù)據(jù)來源。
  • 爬取流程:通過東方財富網(wǎng)得到上交所和深交所的所有股票代碼,將股票代碼依次導入百度股票的url中,即可訪問各股的數(shù)據(jù),再來分析百度股票的HTML頁面爬取相關(guān)數(shù)據(jù)。
  • 工具環(huán)境:python3.6.5,pycharm,win10。

圖片來自拍信

0.網(wǎng)頁分析

想必大家應該不是第一次爬取數(shù)據(jù)了,對于F12開發(fā)者工具有了一定了解,所以這里就不再贅述了。對于數(shù)據(jù)來源,別執(zhí)著于一個網(wǎng)站,可以多分析幾個網(wǎng)站來選擇相對爬取簡單的網(wǎng)站來進行數(shù)據(jù)的爬取。


1.流程分析

東方財富網(wǎng)源代碼

百度股票的URL:http://gupiao.baidu.com/stock/sh502036.html
分析可得:只需將東方財富網(wǎng)中的.html前的股票代碼提取出來并加入到https://gupiao.baidu.com/stock/的后面,便可以得到所有股票源數(shù)據(jù)。
百度股票源代碼數(shù)據(jù)部分


2.函數(shù)設定

依據(jù)流程設定函數(shù)

3.完整代碼

import requests
from bs4 import BeautifulSoup
import traceback
import re
 
def getHTMLText(url, code="utf-8"):
    try:
        r = requests.get(url)
        r.raise_for_status()
        r.encoding = code
        return r.text
    except:
        return ""
 
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])   # 匹配類似sh000001的股票代碼
        except:
            continue
 
def getStockInfo(lst, stockURL, fpath):
    count = 0
    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'})
 
            name = stockInfo.find_all(attrs={'class':'bets-name'})[0]
            infoDict.update({'股票名稱': name.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="")   # \r:能讓輸出比例時不自動換行
        except:
            count = count + 1
            print("\r當前進度: {:.2f}%".format(count*100/len(lst)),end="")
            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()

運行

本練習來自中國大學MOOC

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容