上证指数爬取(四)

作者: ATangYaaaa | 来源:发表于2018-06-13 03:45 被阅读0次

    这次没有创新,仍旧是延续上一篇的scrapy爬取内容,只是工作量有些大。

    爬取新浪财经股票首页的上证指数,每天将日期和收盘价格爬取到数据库中。

    1. 历史数据入库

    新建数据库表格Shangha_composite_index,定义time和price两个项目。从同花顺软件导出上证指数的历史数据到txt文本中,写一个脚本用来将历史数据入库:

    #-*-coding=utf-8-*-

    import re

    import math

    import sqlite3

    f=open('alldata.txt','r')

    datas=f.read()

    f.close()

    times = re.findall('[\d-]+(?=,)',datas)

    g = open('times.txt','w')

    g.close()

    prices = re.findall('\d{2,4}\.?\d{0,2}(?=\n)',datas)

    h = open('prices.txt','w')

    h.close()

    cu=sqlite3.connect("E:\ATang\MyDatabase\SingleData.db")

    L=len(prices)

    print(L)

    for i in range(0,L):

        thetime=times[i]

        theprice=prices[i]

        sql = "insert into Shanghai_composite_index values('%s','%s')" % (thetime,theprice)

        cu.execute(sql)

        cu.commit()

    cu.close()

    最后可以看到数据完全入库了。

    图一 历史数据入库

    2. 爬取更新的上证综合指数数据

    写新的scrapy爬虫爬取更新数据,工作量很小,爬虫代码如下:

    # -*- coding: utf-8 -*-

    import scrapy

    import re

    import sqlite3

    import time

    class StockSpiderSpider(scrapy.Spider):

        name = 'stock_spider'

        allowed_domains = ['sina.com.cn']

        start_urls = ['http://hq.sinajs.cn/rn=1528828126909&list=s_sh000001,s_sz399001,CFF_RE_IC0,rt_hkHSI,gb_$dji,gb_ixic,b_SX5E,b_UKX,b_NKY,hf_CL,hf_GC,hf_SI,hf_CAD']

        def parse(self, response):

            data=re.search(u'(?<=,)\d{4}\.\d{0,4}(?=,)',(response.body)).group()

            print data

            c=sqlite3.connect('E:\ATang\MyDatabase\SingleData.db')

            print "open database successfully"

            now=time.strftime('%Y-%m-%d',time.localtime(time.time()))

            sql="insert into Shanghai_composite_index(time,price) values('%s','%s')"%(now,data)

            c.execute(sql)

            c.commit()

            c.close()

    需要说明的是,爬取的数据来源是长这样的:

    图二 未提取的新数据

    这个爬虫单独运行是可以实现立即爬取一次数据的,但是我觉得这样不好,没办法自动化。于是写了一个时间脚本,让他每天在特定的时候就去抓,不用我担心了。

    3. 时间脚本实现自动化爬取

    时间脚本如下,开机的时候运行就不用管他了,让他自己跑,一旦到固定时间就会抓取一次新数据:

    # -*-coding=utf-8-*-

    # 自动化运行脚本,让指定python脚本在规定时间段运行起来

    # 里面包含的脚本有:

    # 1. 用于抓取新浪微博热搜数据的WeiboResou_spider.py

    #    爬取时间为23:30

    # 2. 抓取上证指数的收盘价

    #    爬取时间为23:45

    #

    #                          2018/06/12

    #                          ATang

    import time

    import os

    def plan():

        while True:

            now = time.strftime("%H:%M", time.localtime())

            now_path=os.getcwd()

            print('I am Working...')

            print('please do not interrupt...')

            print('                                    ATang.')

            print '                                    '+now

            print('------------------------------------------')

            if now == "23:30":

                os.chdir('C:\\Users\\10153\\Scrapy\\weiboresou')

                os.system('python WeiboResou_spider.py')

                print('task_1 over !!! - -')

            elif now == "23:45":

                os.chdir('C:\\Users\\10153\\Scrapy\\stock')

                os.system('scrapy crawl stock_spider')

                print('task_2 over !!! - -')

                return

            time.sleep(60)

    plan()

    好了,这样就可以坐享其成了。等以后稳定了让电脑一直开着,这样脚本就可以稳定输出数据了,想要做数据分析,获得稳定而健康的数据很重要的。

    相关文章

      网友评论

        本文标题:上证指数爬取(四)

        本文链接:https://www.haomeiwen.com/subject/nbydeftx.html