from tkinter import * import urllib.request import re,os import threading from tkinter import filedialog win=Tk() win.title('海啸投资-股票数据下载') win.geometry('200x120+400+200') win.attributes("-toolwindow", 1) win.resizable(width=False,height=False) var = StringVar() var.set('数据量较大,耐心等待!') Label(win,textvariable=var).grid(row=1,column=0,padx=30,pady=10) stock_CodeUrl = 'http://quote.eastmoney.com/stocklist.html' #os.mkdir('stock_data') #获取股票代码列表 def urlTolist(url): allCodeList = [] html = urllib.request.urlopen(url).read() html = html.decode('gbk') s = r'<li><a target="_blank" href="http://quote.eastmoney.com/SS(.*?).html">' pat = re.compile(s) code = pat.findall(html) for item in code: if item[0]=='6' or item[0]=='3' or item[0]=='0': allCodeList.append(item) return allCodeList allCodelist = urlTolist(stock_CodeUrl) def allDown(): fileDir = filedialog.askdirectory() c = len(allCodelist) for code in allCodelist: stemp = '正在获取'+code+'股票数据...' var.set(stemp) #print('正在获取%s股票数据...'%code) if code[0]=='6': url = 'http://quotes.money.163.com/service/chddata.html?code=0'+code+ '&end=20161231&fields=TCLOSE;HIGH;LOW;TOPEN;LCLOSE;CHG;PCHG;TURNOVER;VOTURNOVER;VATURNOVER;TCAP;MCAP' else: url = 'http://quotes.money.163.com/service/chddata.html?code=1'+code+ '&end=20161231&fields=TCLOSE;HIGH;LOW;TOPEN;LCLOSE;CHG;PCHG;TURNOVER;VOTURNOVER;VATURNOVER;TCAP;MCAP' urllib.request.urlretrieve(url,fileDir+'\'+code+'.csv') c-=1 if c==0: var.set('所有股票下载完毕!') def creatDownP(): p = threading.Thread(target = allDown) p.setDaemon(True)#守护进程 p.start() Button(win,text='所有股票下载',width=20,command=creatDownP).grid(row=0,column=0,padx=30,pady=10) mainloop()