您现在的位置: 主页 > 上位机技术 > python > 使用Scrapy爬取股票代码
本文所属标签:
为本文创立个标签吧:

使用Scrapy爬取股票代码

来源:net 网络用户发布,如有版权联系网管删除 2019-02-25 

个人博客:https://mypython.me

源码地址:https://github.com/geeeeeeeek/scrapy_stock

抓取工具:scrapy

scrapy 介绍

Scrapy是一个为了爬取网站数据,提取结构性数据而编写的应用框架。 可以应用在包括数据挖掘,信息处理或存储历史数据等一系列的程序中。其最初是为了页面抓取(更确切来说,网络抓取)所设计的, 也可以应用在获取 API 所返回的数据(例如Amazon Associates Web Services) 或者通用的网络爬虫。

安装 scrapy

pip install Scrapy

抓取步骤

选择一个网站 --> 定义数据 --> 编写 spider

首先使用 scrapy 创建一个项目

scrapy startproject tutorial

1.选择一个网站

这里我们选择的是东方财富网的股票代码页面:http://quote.eastmoney.com/stocklist.html

2.定义要抓取的数据

我们需要抓取股票的代码 id,因此只需要定义 stock_id

class StockItem(scrapy.Item):    stock_id = scrapy.Field()

3.编写 spider

class StockSpider(scrapy.Spider):    name = 'stock'    def start_requests(self):        url = 'http://quote.eastmoney.com/stocklist.html'        yield Request(url)    def parse(self, response):        item = StockItem()        print "===============上海================"        stocks_sh = response.css('div#quotesearch ul li a[href*="http://quote.eastmoney.com/sh"]::text')        for stock in stocks_sh:            item['stock_id'] = 's_sh' + re.findall('((.*?))', stock.extract())[0]            yield item        print "===============深圳================"        stocks_sz = response.css('div#quotesearch ul li a[href*="http://quote.eastmoney.com/sz"]::text')        for stock in stocks_sz:            item['stock_id'] = 's_sz' + re.findall('((.*?))', stock.extract())[0]            yield item

玄机尽在response.css('div#quotesearch ul li a[href*="http://quote.eastmoney.com/sh"]::text ’),使用了 css 来过滤自己需要的数据。

运行程序

scrapy crawl stock -o stock.csv

即可生成 stock.csv 文件

预览如下:

stock_ids_sh201000s_sh201001s_sh201002s_sh201003s_sh201004s_sh201005s_sh201008s_sh201009s_sh201010s_sh202001s_sh202003s_sh202007s_sh203007s_sh203008s_sh203009…

如果要查询单个股票的股票行情,可以使用新浪的股票接口:

http://hq.sinajs.cn

例如

http://hq.sinajs.cn/list=s_sh600756

即可得到浪潮软件的股票行情

var hq_str_s_sh600756="浪潮软件,19.790,1.140,6.11,365843,70869";


              查看评论 回复



嵌入式交流网主页 > 上位机技术 > python > 使用Scrapy爬取股票代码
 一个 数据 抓取

"使用Scrapy爬取股票代码"的相关文章

网站地图

围观()