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基础文件操作方法超详细讲解(详解版)》文件就是操作系统为用户或应用程序提供的一个读写硬盘的虚拟单位,文件的核心操作就是读和写,:本文主要介绍Python基础文件操作方法超详细讲解的相... 目录一、文件操作1. 文件打开与关闭1.1 打开文件1.2 关闭文件2. 访问模式及说明二、文件读写1.

C++变换迭代器使用方法小结

《C++变换迭代器使用方法小结》本文主要介绍了C++变换迭代器使用方法小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录1、源码2、代码解析代码解析:transform_iterator1. transform_iterat

C++中std::distance使用方法示例

《C++中std::distance使用方法示例》std::distance是C++标准库中的一个函数,用于计算两个迭代器之间的距离,本文主要介绍了C++中std::distance使用方法示例,具... 目录语法使用方式解释示例输出:其他说明:总结std::distance&n编程bsp;是 C++ 标准

Python将博客内容html导出为Markdown格式

《Python将博客内容html导出为Markdown格式》Python将博客内容html导出为Markdown格式,通过博客url地址抓取文章,分析并提取出文章标题和内容,将内容构建成html,再转... 目录一、为什么要搞?二、准备如何搞?三、说搞咱就搞!抓取文章提取内容构建html转存markdown

Python获取中国节假日数据记录入JSON文件

《Python获取中国节假日数据记录入JSON文件》项目系统内置的日历应用为了提升用户体验,特别设置了在调休日期显示“休”的UI图标功能,那么问题是这些调休数据从哪里来呢?我尝试一种更为智能的方法:P... 目录节假日数据获取存入jsON文件节假日数据读取封装完整代码项目系统内置的日历应用为了提升用户体验,

vue使用docxtemplater导出word

《vue使用docxtemplater导出word》docxtemplater是一种邮件合并工具,以编程方式使用并处理条件、循环,并且可以扩展以插入任何内容,下面我们来看看如何使用docxtempl... 目录docxtemplatervue使用docxtemplater导出word安装常用语法 封装导出方

Linux换行符的使用方法详解

《Linux换行符的使用方法详解》本文介绍了Linux中常用的换行符LF及其在文件中的表示,展示了如何使用sed命令替换换行符,并列举了与换行符处理相关的Linux命令,通过代码讲解的非常详细,需要的... 目录简介检测文件中的换行符使用 cat -A 查看换行符使用 od -c 检查字符换行符格式转换将

Python FastAPI+Celery+RabbitMQ实现分布式图片水印处理系统

《PythonFastAPI+Celery+RabbitMQ实现分布式图片水印处理系统》这篇文章主要为大家详细介绍了PythonFastAPI如何结合Celery以及RabbitMQ实现简单的分布式... 实现思路FastAPI 服务器Celery 任务队列RabbitMQ 作为消息代理定时任务处理完整

使用Jackson进行JSON生成与解析的新手指南

《使用Jackson进行JSON生成与解析的新手指南》这篇文章主要为大家详细介绍了如何使用Jackson进行JSON生成与解析处理,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 核心依赖2. 基础用法2.1 对象转 jsON(序列化)2.2 JSON 转对象(反序列化)3.

Python Websockets库的使用指南

《PythonWebsockets库的使用指南》pythonwebsockets库是一个用于创建WebSocket服务器和客户端的Python库,它提供了一种简单的方式来实现实时通信,支持异步和同步... 目录一、WebSocket 简介二、python 的 websockets 库安装三、完整代码示例1.