天天看點

python2.7 實作的實時監控指定股票價格的小程式實時監控指定股票價格

實時監控指定股票價格

本文涉及到的python 庫 有 Tkinter,sys,urllib2,time

在開始之前我們首先要确定股票資訊的來源,在此以東方财富網為例,在分析網站的過程中發現直接讀取HTML源代碼是抓不到資料的,很顯然該頁面使用了AJAX動态的請求資料在頁面顯示,因而我們隻要簡單的擷取到這個api就好了。

- 擷取東方财富網查詢股票資訊的api

- 使用urllib2

- 使用Tkinter庫編寫GUI程式

使用Google浏覽器開發者工具擷取api F12

在首頁随便查一隻股票

python2.7 實作的實時監控指定股票價格的小程式實時監控指定股票價格

以300101為例,F12打開開發者工具,檢視頁面加載的js,依次排查response資料找到我們需要的結果

python2.7 實作的實時監控指定股票價格的小程式實時監控指定股票價格

複制請求連接配接

python2.7 實作的實時監控指定股票價格的小程式實時監控指定股票價格

請求URL容:

http://nufm.dfcfw.com/EM_Finance2014NumericApplication/JS.aspx?type=CT&cmd=3001012&sty=CTBF&st=z&sr=&p=&ps=&cb=var%20pie_data=&js=(x)&token=28758b27a75f62dc3065b81f7facb365&_=1497258906443

在浏覽器直接送出該連結看一下效果

python2.7 實作的實時監控指定股票價格的小程式實時監控指定股票價格

非常完美正是我們想要的結果。

接下來就是碼代碼實作邏輯了。

基本需求,因為要上班,時不時的打開手機看股票或者開網頁去看,被上司看到了影響會不好,因而做一個小視窗,放在桌面上檢視很友善也很隐蔽。是以程式要滿足如下需求,視窗小巧,隻顯示股票價格主要資訊,能根據輸入的股票代碼查詢資訊。

代碼如下

# -*- coding:utf-8 -*-
#檢視股票實時價格

__author__ = 'zyy'
from Tkinter import *
import sys,urllib2,time

count = 
root = Tk()
title = Label(root,text=u'股票代碼')
title.pack()
l_stock_no = Entry(root)
l_stock_no.pack()
content = Label(root,text=u'實時行情')
content.pack()
class StockMonitor(Frame):
    msec =  
    def __init__(self,parent=None,**kw):
        Frame.__init__(self,parent,kw)
        self._running = False
        self.c_date = StringVar()
        self.c_time = StringVar()
        self.stockinfo  = StringVar()
        self.flag = True
        self.makeWidget()

    def makeWidget(self):
        label_date = Label(self,textvariable=self.c_date)
        label_date.pack()
        label_time = Label(self,textvariable=self.c_time)
        label_time.pack()
        label_stock = Label(self,textvariable=self.stockinfo)
        label_stock.pack()

        btn_start = Button(self,text='start',command=self.start)
        btn_start.pack(side=LEFT)
        btn_end = Button(self,text='end',command=self.quit)
        btn_end.pack(side=LEFT)

    def get_stock_info(self,stock_no,num_retries=):
        try:
            url = 'http://nufm.dfcfw.com/EM_Finance2014NumericApplication/JS.aspx?type=CT&cmd='+stock_no.strip()+'2&sty=CTBF&st=z&sr=&p=&ps=&cb=var%20pie_data=&js=(x)&token=28758b27a75f62dc3065b81f7facb365&_=1496312544427'
            headers = {'User-agent':'WSWP'}
            request = urllib2.Request(url,headers=headers)
            page = urllib2.urlopen(request)
            page_content = page.read()
        except urllib2.URLError as e:
            print  'download error:',e.reason
            page_content = None
            if num_retries > :
                if hasattr(e,'code' and  <= e.code <):
                    # recursively retry 5xx HTTP errors
                    return get_stock_info(stock_no,num_retries-)
        return page_content

    def _update(self):
        self._set_count()
        self.timer = self.after(self.msec,self._update)

    def _set_count(self):

        stock_info = self.get_stock_info(l_stock_no.get())
        if stock_info is not None:
            stock_info = stock_info[:]
        today1 = str(time.strftime('%Y-%m-%d', time.localtime(time.time())))
        time1 = str(time.strftime('%H:%M:%S', time.localtime(time.time())))
        self.stockinfo.set(stock_info)
        self.c_date.set(today1)
        self.c_time.set(time1)

    def start(self):
        self._update()
        self.pack(side = TOP)



def main():

    stock = StockMonitor(root)
    stock.pack(side = BOTTOM)
    root.mainloop()
    root.geometry('350x250')

if __name__ == '__main__':
    main()

           

将Python 程式打包成可執行檔案,使用pyinstaller 工具,使用方法可參考官網

http://www.pyinstaller.org/

PyInstaller Quickstart

Install PyInstaller from PyPI:

pip install pyinstaller

Go to your program’s directory and run:

pyinstaller yourprogram.py

如果出現UnicodDecodeError:ascii codec can’t decode byte …等等錯誤,找到出錯的python 檔案 ,在源碼裡開頭加上如下代碼

if sys.getdefaultencoding() != 'gbk': 
 reload(sys) 
 sys.setdefaultencoding('gbk')
           

本例打包指令如下

>> pyinstaller -F -w stockmonitor.py
           

參數說明 :

-F, –onefile Py代碼隻有一個檔案

-D, –onedir Py代碼放在一個目錄中(預設是這個)

-K, –tk 包含TCL/TK

-d, –debug 生成debug模式的exe檔案

-w, –windowed, –noconsole 窗體exe檔案(Windows Only)

-c, –nowindowed, –console 控制台exe檔案(Windows Only)

X, –upx 使用upx壓縮exe檔案

-o DIR, –out=DIR 設定spec檔案輸出的目錄,預設在PyInstaller同目錄

–icon=FILE.ICO 加入圖示(Windows Only)

-v FILE, –version=FILE 加入版本資訊檔案

效果圖如下

python2.7 實作的實時監控指定股票價格的小程式實時監控指定股票價格