用Python爬取最新股票数据含完整源代码

用Python爬取最新股票数据含完整源代码
抓取目标:
url:http://webapi.cninfo.com.cn/#/marketDataDate
数据目标: 获取 证券代码 证券简称 交易日期 开盘价 最高价 最低价 收盘价 成交数量
难点: 请求头参数mcode 加密生成
使用第三方库:

  1. requests

  2. execjs

  3. js2py

  4. math

  5. time

  6. pandas

工具:

  1. 谷歌浏览器
  2. pycharm
  3. python3.7
    爬取到的股票数据存入到code.xlsx,可设定需要爬取的时间范围
    在这里插入图片描述
    完整代码
import requests
import execjs
import js2py
import math
import time
import pandas as pd

code_list = []


def MCODE():
    jscode = '''
    function missjson(input) {  
        var keyStr = "ABCDEFGHIJKLMNOP" + "QRSTUVWXYZabcdef" + "ghijklmnopqrstuv"   + "wxyz0123456789+/" + "=";  
        var output = "";  
        var chr1, chr2, chr3 = "";  
        var enc1, enc2, enc3, enc4 = "";  
        var i = 0;  
        do {  
            chr1 = input.charCodeAt(i++);  
            chr2 = input.charCodeAt(i++);  
            chr3 = input.charCodeAt(i++);  
            enc1 = chr1 >> 2;  
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);  
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);  
            enc4 = chr3 & 63;  
            if (isNaN(chr2)) {  
                enc3 = enc4 = 64;  
            } else if (isNaN(chr3)) {  
                enc4 = 64;  
            }  
            output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2)  
                    + keyStr.charAt(enc3) + keyStr.charAt(enc4);  
            chr1 = chr2 = chr3 = "";  
            enc1 = enc2 = enc3 = enc4 = "";  
        } while (i < input.length);  

        return output;  
    } 

    '''
    time1 = js2py.eval_js('Math.floor(new Date().getTime()/1000)')
    # py方式
    a = math.floor(time.time() / 1000)
    mcode = execjs.compile(jscode).call('missjson', '{a}'.format(a=time1))
    return mcode


def PageRquest(datetime, mcode):
    # 接口可以换
    url = 'http://webapi.cninfo.com.cn/api/sysapi/p_sysapi1015'
    data = {
        'tdate': datetime,  # 获取数据时间
        'scode': '399001'  # 股票代码 以及交易所简称
    }
    headers = {
        'mcode': str(mcode),
        'Referer': 'http://webapi.cninfo.com.cn/',
        'Cookie': 'Hm_lvt_489bd07e99fbfc5f12cbb4145adb0a9b=1634795282; Hm_lpvt_489bd07e99fbfc5f12cbb4145adb0a9b=1634799860',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36'
    }
    response = requests.post(url, headers=headers, data=data).json()
    code = response['records']
    for i in code:
        code_list.append(i)


def main(date):
    mcode = MCODE()
    PageRquest(date, mcode)


if __name__ == '__main__':
    # main()
    # 数据分析 pandas 自动化办公的
    datetime = pd.period_range('2021/5/26', '2021/10/27', freq='B')
    for date in datetime:
        main(date)
    df = pd.DataFrame(code_list)
    print(df)
    df.to_excel('code.xlsx')

更多Python源代码,请微信关注:Python代码大全,
在这里插入图片描述

  • 0
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
以下是一个简单的示例,展示如何使用Python爬取数据并将其存储到MySQL数据库中。 首先,需要安装Python的MySQL连接器。可以使用以下命令安装: ``` pip install mysql-connector-python ``` 接下来,我们需要编写代码来连接到MySQL数据库并创建表,以便我们可以将数据存储在其中。下面是一个示例代码: ```python import mysql.connector # 连接数据库 mydb = mysql.connector.connect( host="localhost", user="yourusername", password="yourpassword", database="mydatabase" ) # 创建表 mycursor = mydb.cursor() mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))") ``` 接下来,我们可以使用Python的requests库从网站中获取数据。以下是一个示例代码: ```python import requests url = 'https://www.example.com/data' response = requests.get(url) data = response.json() ``` 现在,我们有了数据,我们可以将其存储在MySQL数据库中。以下是一个示例代码: ```python import mysql.connector # 连接数据库 mydb = mysql.connector.connect( host="localhost", user="yourusername", password="yourpassword", database="mydatabase" ) # 插入数据 mycursor = mydb.cursor() sql = "INSERT INTO customers (name, address) VALUES (%s, %s)" val = ("John", "Highway 21") mycursor.execute(sql, val) mydb.commit() print(mycursor.rowcount, "record inserted.") ``` 以上是一个简单的示例代码,展示如何使用Python数据爬取并存储到MySQL数据库中。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Python代码大全

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值