栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

使用scrapy抓取股票代码

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用scrapy抓取股票代码

个人博客: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

  1. 定义要抓取的数据

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

class StockItem(scrapy.Item):
    stock_id = scrapy.Field()
  1. 编写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_id
s_sh201000
s_sh201001
s_sh201002
s_sh201003
s_sh201004
s_sh201005
s_sh201008
s_sh201009
s_sh201010
s_sh202001
s_sh202003
s_sh202007
s_sh203007
s_sh203008
s_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";
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/220658.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号