天天看點

使用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";