本文对中国大学慕课上《Python网络爬虫与信息提取》课程中的最后一个实例“股票数据Scrapy爬虫”给出了具体的更新后的实现步骤。
课程中介绍的是采用百度股票和东方财富网,但由于百度股票已不可访问,故此处采用的是证券之星和网易财经。
建立一个Scrapy爬虫工程:
通过命令指示符在目录D:\pycodes(你所希望将项目存储的位置)下执行命令 “scrapy startproject Stocks”,建立一个名为“Stocks”的工程,如图所示:
可查看在该项目中生成了多个文件,如图所示:
在工程中创建一个爬虫:
通过命令指示符在目录D:\pycodes\Stocks下执行命令“scrapy genspider stocks quote.stockstar.com”,“stocks”为爬虫文件名,“quote.stockstar.com”为爬虫页面的初始域名,如图所示:
可在项目中观察到多了一个文件“stocks.py”,如图所示:
更改爬取方法的具体功能,具体代码:
(1)打开“stocks.py”文件,修改代码,如下所示:
import re
import scrapy
class StocksSpider(scrapy.Spider):
name = 'stocks'
start_urls = ['http://quote.stockstar.com/stock/stock_index.htm']
def parse(self, response):
for href in response.css('a::attr(href)').extract():
try:
stock = re.search(r'/gs/sh_\d{6}.shtml', href).group(0).split('_')[1].split('.')[0]
url = "http://quotes.money.163.com/" + '0' + stock + '.html'
yield scrapy.Request(url=url, callback=self.parse_stock)
except:
continue
def parse_stock(self, response):
infoDict = {
}
script = response.xpath('//div[@class="relate_stock clearfix"]/script[1]').extract()
info = script[0].strip().split(',')
infoDict['股票名称'] = eval(re.search(r'name\: \'.*\'', info[0]).group(0).split(':')[1])
infoDict['股票代码'] = eval(re.search(r'code\: \'\d{6}\'', info[1]).group(0).split(":")[1])
infoDict['现价'] = eval(re.search(r'price\: \'.*\'', info[2]).group(0).split(":")[1])
infoDict['涨跌幅'] = re.search(r'change\: \'.*%', info[3]).group(0).split("'")[1]
infoDict['昨收'] = eval(re.search(r'yesteday\: \'.*\'', info[4]).group(0).split(":")[1])
infoDict['今开'] = eval(re.search(r'today\: \'.*\'', info[5]).group(0).split(":")[1])
infoDict['最高'] = eval(re.search(r'high\: \'.*\'', info[6]).group(0).split(":")[1])
infoDict['最低'] = eval(re.search(r'low\: \'.*\'', info[7]).group(0).split(":")[1])
yield infoDict
(2)打开“pipelines.py”文件,修改代码,如下所示:
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
class ScrapystocksPipeline(object):
def process_item(self, item, spider):
return item
class ScrapystocksInfoPipeline(object):
def open_spider(self, spider): #爬虫启动,对应的pipeline方法
self.f = open('ScrapyStockInfo.txt', 'w')
def close_spider(self, spider): #爬虫关闭,对应的pipeline方法
self.f.close()
def process_item(self, item, spider): #核心部分,存储为文件
try:
line = str(dict(item)) + '\n'
self.f.write(line)
except:
pass
return item
(3)打开“settings.py”文件,修改部分代码,如下所示:
原代码:
#ITEM_PIPELINES = {
# 'Stocks.pipelines.StocksPipeline': 300,
#}
修改后:去掉注释,修改pipeline类名称
ITEM_PIPELINES = {
'Stocks.pipelines.ScrapystocksInfoPipeline': 300,
}