python爬虫进阶篇:Scrapy中使用Selenium+Firefox浏览器爬取沪深A股股票行情

本文主要是介绍python爬虫进阶篇:Scrapy中使用Selenium+Firefox浏览器爬取沪深A股股票行情,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、前言

上篇记录了Scrapy搭配selenium的使用方法,有了基本的了解后我们可以将这项技术落实到实际需求中。目前很多股票网站的行情信息都是动态数据,我们可以用Scrapy+selenium对股票进行实时采集并持久化,再进行数据分析、邮件通知等操作。

二、环境搭建

详情请看上篇笔记

三、代码实现

  • items
class StockSpiderItem(scrapy.Item):# define the fields for your item here like:# name = scrapy.Field()# 股票代码stock_code = scrapy.Field()# 股票名称stock_name = scrapy.Field()# 最新价last_price = scrapy.Field()# 涨跌幅rise_fall_rate = scrapy.Field()# 涨跌额rise_fall_price = scrapy.Field()
  • middlewares
	def __init__(self):# ----------------firefox的设置------------------------------- #self.options = firefox_options()def spider_opened(self, spider):spider.logger.info('Spider opened: %s' % spider.name)spider.driver = webdriver.Firefox(options=self.options)  # 指定使用的浏览器def process_request(self, request, spider):# Called for each request that goes through the downloader# middleware.# Must either:# - return None: continue processing this request# - or return a Response object# - or return a Request object# - or raise IgnoreRequest: process_exception() methods of#   installed downloader middleware will be calledspider.driver.get("https://quote.eastmoney.com/center/gridlist.html#hs_a_board")return Nonedef process_response(self, request, response, spider):# Called with the response returned from the downloader.# Must either;# - return a Response object# - return a Request object# - or raise IgnoreRequestresponse_body = spider.driver.page_sourcereturn HtmlResponse(url=request.url, body=response_body, encoding='utf-8', request=request)
  • settings设置
# See https://doc.scrapy.org/en/latest/topics/spider-middleware.html
SPIDER_MIDDLEWARES = {'stock_spider.middlewares.StockSpiderSpiderMiddleware': 543,
}# Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
DOWNLOADER_MIDDLEWARES = {'stock_spider.middlewares.StockSpiderDownloaderMiddleware': 543,
}
  • spider文件
    def parse(self, response):# 股票代码stock_code = response.css("table.table_wrapper-table tbody tr td:nth-child(2) a::text").extract()# 股票名称stock_name = response.css("table.table_wrapper-table tbody tr td:nth-child(3) a::text").extract()# 最新价last_price = response.css("table.table_wrapper-table tbody tr td:nth-child(5) span::text").extract()# 涨跌幅rise_fall_rate = response.css("table.table_wrapper-table tbody tr td:nth-child(6) span::text").extract()# 涨跌额rise_fall_price = response.css("table.table_wrapper-table tbody tr td:nth-child(7) span::text").extract()for i in range(len(stock_code)):item = StockSpiderItem()item["stock_code"] = stock_code[i]item["stock_name"] = stock_name[i]item["last_price"] = last_price[i]item["rise_fall_rate"] = rise_fall_rate[i]item["rise_fall_price"] = rise_fall_price[i]yield itemdef close(self, spider):spider.driver.quit()
  • pipelines持久化
    def process_item(self, item, spider):"""接收到提交过来的对象后,写入csv文件"""filename = f'stock_info.csv'with open(filename, 'a+', encoding='utf-8') as f:line = item["stock_code"] + "," + item["stock_name"] + "," + item["last_price"] + "," + \item["rise_fall_rate"] + "," + item["rise_fall_price"] + "\n"f.write(line)return item
  • readme文件
1.安装依赖包 
- python 3.0+
- pip install -r requirements.txt2.将最第二层stock_spider文件夹设置为根目录3.将firefox驱动程序包放到python环境的Scripts文件夹里4.必须要安装firefox浏览器才会调用到浏览器5.执行spider_main.py文件启动爬虫

这篇关于python爬虫进阶篇:Scrapy中使用Selenium+Firefox浏览器爬取沪深A股股票行情的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/528898

相关文章

使用Python实现矢量路径的压缩、解压与可视化

《使用Python实现矢量路径的压缩、解压与可视化》在图形设计和Web开发中,矢量路径数据的高效存储与传输至关重要,本文将通过一个Python示例,展示如何将复杂的矢量路径命令序列压缩为JSON格式,... 目录引言核心功能概述1. 路径命令解析2. 路径数据压缩3. 路径数据解压4. 可视化代码实现详解1

python获取网页表格的多种方法汇总

《python获取网页表格的多种方法汇总》我们在网页上看到很多的表格,如果要获取里面的数据或者转化成其他格式,就需要将表格获取下来并进行整理,在Python中,获取网页表格的方法有多种,下面就跟随小编... 目录1. 使用Pandas的read_html2. 使用BeautifulSoup和pandas3.

Pandas透视表(Pivot Table)的具体使用

《Pandas透视表(PivotTable)的具体使用》透视表用于在数据分析和处理过程中进行数据重塑和汇总,本文就来介绍一下Pandas透视表(PivotTable)的具体使用,感兴趣的可以了解一下... 目录前言什么是透视表?使用步骤1. 引入必要的库2. 读取数据3. 创建透视表4. 查看透视表总结前言

Python装饰器之类装饰器详解

《Python装饰器之类装饰器详解》本文将详细介绍Python中类装饰器的概念、使用方法以及应用场景,并通过一个综合详细的例子展示如何使用类装饰器,希望对大家有所帮助,如有错误或未考虑完全的地方,望不... 目录1. 引言2. 装饰器的基本概念2.1. 函数装饰器复习2.2 类装饰器的定义和使用3. 类装饰

Python 交互式可视化的利器Bokeh的使用

《Python交互式可视化的利器Bokeh的使用》Bokeh是一个专注于Web端交互式数据可视化的Python库,本文主要介绍了Python交互式可视化的利器Bokeh的使用,具有一定的参考价值,感... 目录1. Bokeh 简介1.1 为什么选择 Bokeh1.2 安装与环境配置2. Bokeh 基础2

SpringBoot UserAgentUtils获取用户浏览器的用法

《SpringBootUserAgentUtils获取用户浏览器的用法》UserAgentUtils是于处理用户代理(User-Agent)字符串的工具类,一般用于解析和处理浏览器、操作系统以及设备... 目录介绍效果图依赖封装客户端工具封装IP工具实体类获取设备信息入库介绍UserAgentUtils

Android使用ImageView.ScaleType实现图片的缩放与裁剪功能

《Android使用ImageView.ScaleType实现图片的缩放与裁剪功能》ImageView是最常用的控件之一,它用于展示各种类型的图片,为了能够根据需求调整图片的显示效果,Android提... 目录什么是 ImageView.ScaleType?FIT_XYFIT_STARTFIT_CENTE

Java学习手册之Filter和Listener使用方法

《Java学习手册之Filter和Listener使用方法》:本文主要介绍Java学习手册之Filter和Listener使用方法的相关资料,Filter是一种拦截器,可以在请求到达Servl... 目录一、Filter(过滤器)1. Filter 的工作原理2. Filter 的配置与使用二、Listen

Pandas使用AdaBoost进行分类的实现

《Pandas使用AdaBoost进行分类的实现》Pandas和AdaBoost分类算法,可以高效地进行数据预处理和分类任务,本文主要介绍了Pandas使用AdaBoost进行分类的实现,具有一定的参... 目录什么是 AdaBoost?使用 AdaBoost 的步骤安装必要的库步骤一:数据准备步骤二:模型

使用Pandas进行均值填充的实现

《使用Pandas进行均值填充的实现》缺失数据(NaN值)是一个常见的问题,我们可以通过多种方法来处理缺失数据,其中一种常用的方法是均值填充,本文主要介绍了使用Pandas进行均值填充的实现,感兴趣的... 目录什么是均值填充?为什么选择均值填充?均值填充的步骤实际代码示例总结在数据分析和处理过程中,缺失数