python 实时获取股票行情脚本 协程版

震惊!一名中年韭菜竟然打算使用python来翻身?

震惊!!某中年韭菜竟然又打算使用Python的协程翻身?

震惊三部曲之终篇,本篇主要优化爬取数据脚本,使用协程加快速度。

1. aiohttp介绍

Async HTTP client/server for asyncio and Python. 

asyncio和Python的异步HTTP客户端/服务器,其实aiohttp就是基于asyncio实现的HTTP框架。

由于脚本中获取数据是需要访问http接口的,所以加上这个HTTP框架,会显得高大上。

2. 用法

首先,官方推荐使用ClientSession来管理会话。asyncio实现单线程并发IO操作

复习一下asyncio的用法

3. 实现

首先将访问接口的方法定义为协程函数,使用ClientSession管理会话

然后将需要访问的链接做好处理,传入getData(),加入任务列表

最后启动协程异步操作任务,完成!码:

import json
import time
import asyncio
import aiohttp
import pymysql

now = lambda :time.time()

code_list = []

dbconf = {'host':'127.0.0.1',
                'port':3306,
                'user':'root',
                'password':'root',
                'db':'shares',
                'charset':'utf8mb4',
                'cursorclass':pymysql.cursors.DictCursor}


def execsql(sql, databaseconf):
    '''connect mysql return result'''
    try:
        conn = pymysql.connect(**databaseconf)
        with conn.cursor() as cursor:
            try:
                cursor.execute(sql)
                conn.commit()
                # print('Commit!')
            except Exception as e:
                print(e)
        conn.close()

    except Exception as e:
        print(e)


async def getData(url):

    async with aiohttp.ClientSession() as session:
    try:
        async with session.get(url,timeout=60) as r:
				shares = await r.text()
				share = json.loads(shares[9:-1])
				data = share["Value"]
                if len(data) > 0:
					date = data[49][:-9]
					sql = 'insert into share_copy1(name,code,now,rise,changehands,amplitude,priceearnings,marketrate,date) values("{name}","{code}","{now}","{rise}","{changehands}","{amplitude}","{priceearnings}","{marketrate}","{date}")'.format(name=data[2],code=data[1],now=data[25],rise=data[29],changehands=data[37],amplitude=data[50],priceearnings=data[38],marketrate=data[43],date=date)
await execsql(sql,dbconf)
					print(sql)
                else :
					print(f'已退市或板块代码:{url}')
    except Exception as e:
			print(f'访问超时:{url}\n'+ str(e))


def share_code():
    with open('sh_info.txt', 'rU') as file:
        for code in file.readlines():
            code_list.append(code.strip())

def main():

    share_code()

    start = now()

    tasks = []

    try:
        for code in code_list:
            if code[:2] == '60':
                sh_url = 'http://nuff.eastmoney.com/EM_Finance2015TradeInterface/JS.ashx?id={code}1'.format(code=code)
                tasks.append(asyncio.ensure_future(getData(sh_url)))
            else:
                sz_url = 'http://nuff.eastmoney.com/EM_Finance2015TradeInterface/JS.ashx?id={code}2'.format(code=code)
                tasks.append(asyncio.ensure_future(getData(sz_url)))
    except Exception as e:
        print(e)

    loop=asyncio.get_event_loop()

    finished, unfinished = loop.run_until_complete(asyncio.wait(tasks,return_when=asyncio.ALL_COMPLETED))

    fin = len(finished)
    unfin = len(unfinished)

    loop.close()

    print(f'完成:{fin},未完成:{unfin}')
    print('Time:',now() - start)
        

if __name__=="__main__":
    main()

执行结果:

嗯,78s,比之前快好几倍了,暂时够用。

代码比较简陋,功能也单一,但用来练手还是可以的。有条件的同学可以找下其他更好用的接口。

最近市场震荡不停,还是且买且看看。

 

 

扫码关注,获取精选资源

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值