开发者社区> 问答> 正文

如何实时爬取股股市行情?

如何实时爬取股股市行情?

一. 数据来源准备
想爬取收集目前A股所有股票的每日行情做分析,首先要找到很全的上市公司股票代码信息,然后通过市面上已有的免费的股票数据api接口获取,接着将获取到的数据进行存储,最后数据存储到一定量后,就可以对数据进行分析。

1. 股票代码

沪市:

http://www.sse.com.cn/assortment/stock/list/share/)

深市:

http://www.szse.cn/market/companys/company/index.html

以上交易所网站可以获取到目前A股上所有上市公司股票代码信息。

2. api接口

我所知的接口有新浪、和讯、东方财富网,本文中使用的是东方财富网提供的接口,挺好用的,数据也很全。

测试一下(浏览器输入):

http://nuff.eastmoney.com/EM_Finance2015TradeInterface/JS.ashx?id=6000001

会得到返回结果:

二. 主要模块
这次主要涉及到的模块有requests、pymysql、json这3个。

requests库是一个常用的用于http请求的模块,可以方便的对网页进行爬取,是学习python爬虫的较好的http请求模块。

pymysql是在Python3.x版本中用于连接MySQL服务器的一个库。

Json模块则是提供了把内存中的对象序列化的方法。例如:loads()、dumps()

三. 实现
1. get请求获取数据

import requests
import json
##get方法发送http请求
response = requests.get(url='http://nuff.eastmoney.com/EM_Finance2015TradeInterface/JS.ashx?id=6000001')
##得到response返回信息
shares = response.text
 
share = json.loads(shares[9:-1])
 
print(type(share)) ## <class 'dict'>
print(share)

**json.loads(shares[9:-1]):**由于返回的是string字符类型数据callback(...),所以通过切片将里面的看起来像是字典样式的数据截取出来,再通过json.loads方法转化为dict类型数据。

2. 数据库操作

import pymysql
 
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)
                ##执行增删改操作后需要commit
                conn.commit()
 
            except Exception as e:
                print(e)
                cursor.close()
        conn.close()
 
    except Exception as e:
        print(e)

conn.cursor()游标

需要提前将数据库以及表结构,提前创建好。

执行insert语句即可将数据插入到数据库中:

sql = 'insert into share(name,code) values("浦发银行","600000")'
execsql(sql,dbconf)

3. 其他操作

1) 读取所有股票代码
预先将交易所网上的股票代码下载下来汇总到一个文件中

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

2) 处理接口url
由于这个接口分为沪市与深市,区别就在接口url的最后一个字符,1表示沪市、2表示深市。所以需要判断代码前2个字符,为60则是沪市,使用1,其余均使用2。

http://nuff.eastmoney.com/.../JS.ashx?id=6000001

http://nuff.eastmoney.com/.../JS.ashx?id=0000022

if code[:2] == '60':
    sh_url = 'http://nuff.eastmoney.com/EM_Finance2015TradeInterface/JS.ashx?id={code}1'.format(code=code)
else:
    sz_url = 'http://nuff.eastmoney.com/EM_Finance2015TradeInterface/JS.ashx?id={code}2'.format(code=code)

四. 完成

##所有代码
import requests
import json
import pymysql
 
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()
            except Exception as e:
                print(e)
                cursor.close()
        conn.close()
 
    except Exception as e:
        print(e)
 
 
def share_code():
    with open('sh_info.txt', 'rU') as file:
        for code in file.readlines():
            code_list.append(code.strip())
 
    print(code_list)
 
 
def insert_db(url):
    response = requests.get(url)
    shares = response.text
    share = json.loads(shares[9:-1])
    data = share["Value"]
    date = data[49][:-9]
    sql = 'insert into share(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)
 
    execsql(sql,dbconf)
    print(sql)
 
def main():
    share_code()
    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)
            try:
                insert_db(sh_url)
            except Exception as e:
                print(e)
        else:
            sz_url = 'http://nuff.eastmoney.com/EM_Finance2015TradeInterface/JS.ashx?id={code}2'.format(code=code)
            try:
                insert_db(sz_url)
            except Exception as e:
                print(e)
 
if __name__=="__main__":
    main()

美化封装以上代码,每日下午3点收盘后执行一遍,就可以得到以下结果:
image.png

原文链接

技术交流群

群福利:群内每周进行群直播技术分享及问答

image

展开
收起
珍宝珠 2020-01-06 14:40:36 5901 0
2 条回答
写回答
取消 提交回答
  • 这个太666了

    2020-01-09 09:36:02
    赞同 展开评论 打赏
  • 这个太666了

    2020-01-08 13:09:25
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
社交数据分析-好友推荐 立即下载
QQ空间平台百亿级流量广告系统海量服务实践 立即下载
电商平台优化纪实 立即下载