1. 程式人生 > >python爬蟲學習 之 定向爬取 股票資訊

python爬蟲學習 之 定向爬取 股票資訊

一、功能描述
目標:獲取上交所和深交所所有股票的名稱和交易 資訊
輸出:儲存到檔案中

技術路線:requests-bs4-re

二、
選取原則:股票資訊靜態存在於HTML頁面中,非js程式碼生成,沒有robots協議限制

三、程式的結構設計
1、從東方財富網獲取股票列表
2、根據股票列表逐個到百度股票獲取個股資訊
3、將結果儲存到檔案

四、

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) #得到具體單支股票頁面的html try
: if html == "": continue infoDict={} soup = BeautifulSoup(html,"html.parser") stockInfo = soup.find("div", attrs={"class":"stock-bets"}) #找到屬性為"class":"stock-bets",名稱為div的標籤 name = stockInfo.find(attrs={"class":"bets-name"}) #在div標籤中,找到屬性為"class":"bets-name"的標籤 infoDict.update({"股票名稱":name.text.split()[0]}) #字典新增鍵值對,其中name.text為name標籤中的文字資訊,包括換行符和空字元,利用split()函式後,返回股票名字和標號的列表。 keyList = stockInfo.find_all("dt") #在div標籤中,找到所有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()

五、針對上述程式碼的改進

import requests
from bs4 import BeautifulSoup
import traceback
import re

def getHTMLText(url,code='utf-8'):#加入一個形參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])
        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(attrs={'class':'bets-name'})

            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()