《Python網絡爬蟲與信息提取》第三週 網絡爬蟲之實戰 學習筆記(三)“股票數據定向爬蟲”實例

目錄

三、“股票數據定向爬蟲”實例

1、“股票數據定向爬蟲”實例介紹

(1)功能描述

(2)候選數據網站的選擇

(3)程序的結構設計

2、“股票數據定向爬蟲”實例編寫

3、“股票數據定向爬蟲”實例優化

(1)速度提高:編碼識別的優化

(2)體驗提高:增加動態進度顯示


三、“股票數據定向爬蟲”實例

1、“股票數據定向爬蟲”實例介紹

(1)功能描述

目標:獲取上交所和深交所所有股票的名稱和交易信息。

輸出:保存到文件中。

技術路線:requests­-bs4-­re。

(2)候選數據網站的選擇

①新浪股票:http://finance.sina.com.cn/stock/

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

備註:原來的百度股票網頁鏈接已失效;故更改爲https://so.cfi.cn/so.aspx?txquery=。原來的東方財富網網頁鏈接已無法爬取數據;故更改爲http://quote.eastmoney.com/stock_list.html#sh

選取原則:股票信息靜態存在於HTML頁面中,非js代碼生成,沒有Robots協議限制。

選取方法:瀏覽器F12,源代碼查看等。

選取心態:不要糾結於某個網站,多找信息源嘗試。

(3)程序的結構設計

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

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

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

2、“股票數據定向爬蟲”實例編寫

# “股票數據定向爬蟲”實例編寫
# 錯誤
import requests
from bs4 import BeautifulSoup
import traceback
import re

def getHTMLText(url):
    try:
        r = requests.get(url, timeout=30)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return ""


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'})

            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')
        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 = 'H://python//Web crawler//BaiduStockInfo.txt'
    slist = []
    getStockList(slist, stock_list_url)
    getStockInfo(slist, stock_info_url, output_file)


main()

# “股票數據定向爬蟲”實例編寫
# 正確
import requests
from bs4 import BeautifulSoup
import traceback
import re

def getHTMLText(url, code='utf-8'):
    try:
        r = requests.get(url, timeout=30)
        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])
        except:
            continue
    return lst


def getStockInfo(lst, stockURL, fpath):
    count = 0
    for stock in lst:
        url = stockURL + stock + ".html"
        html = getHTMLText(url)
        try:
            if html == "" or html == None:
                continue
            l = []
            soup = BeautifulSoup(html, 'html.parser')
            stockInfo = soup.find('table', attrs={'class': 'quote'})
            trans = str(stockInfo)
            reg = r'<td>(.*?)</td>'
            texty = re.compile(reg)
            s1 = re.findall(texty, trans)[1::]
            reg1 = r'<td>(.*?)<a'
            texty1 = re.compile(reg1)
            s2 = re.findall(texty1, trans)[0]
            for i in s1:
                s = i.replace("\u3000", "")
                x = s.replace("<span style=\"color:rgb(0,102,0)\">", "")
                b = x.replace("<span style=\"color:rgb(0,0,0)\">", "")
                a = b.replace("</span>", "")
                c = a.replace("<span style=\"color:rgb(255,0,0)\">", "")
                l.append(c)
            w = ",".join(l)
            if l == []:
                continue

            with open(fpath, 'a', encoding='utf-8') as f:
                f.write(s2 + '\u3000')
                f.write(w + '\n')
                count = count + 1
                print("\r當前速度:{:.2f}%".format(count * 100 / len(lst)), end="")  # 增加動態進度顯示。
        except:
            count = count + 1
            print("\r當前速度:{:.2f}%".format(count * 100 / len(lst)), end="")  # 增加動態進度顯示。
            continue


def main():
    stock_list_url = 'http://quote.eastmoney.com/stock_list.html#sh'
    stock_info_url = 'https://so.cfi.cn/so.aspx?txquery=sz501310'
    output_file = 'H://python//Web crawler//BaiduStockInfo.txt'
    slist = []
    getStockList(slist, stock_list_url)
    print(getStockInfo(slist, stock_info_url, output_file))


main()

備註:原來的網頁鏈接(http://quote.eastmoney.com/stock_list.html#sh)爬取時間太長;故更改爲https://so.cfi.cn/so.aspx?txquery=sz501310,等號後的sz501310是對應每個股的代號。運行時間大約2000分鐘。(運行時間沒寫錯,確實很長)

3、“股票數據定向爬蟲”實例優化

(1)速度提高:編碼識別的優化

def getHTMLText(url):
    try:
        r = requests.get(url, timeout=30)
        r.raise_for_status()
        r.encoding = r.apparent_encoding  # 編碼識別的優化。
        return r.text
    except:
        return ""

(2)體驗提高:增加動態進度顯示

            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:
            count = count + 1
            print("\r當前速度:{:.2f}%".format(count * 100 / len(lst)), end="")  # 增加動態進度顯示。
            continue

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章