python爬虫进阶篇:Scrapy中使用Selenium+Firefox浏览器爬取国债逆回购并发送QQ邮件通知

news/2024/7/19 11:54:30 标签: python, 爬虫, scrapy

一、前言

每到年底国债逆回购的利息都会来一波高涨,利息会比银行的T+0的理财产品的利息高,所以可以考虑写个脚本每天定时启动爬取逆回购数据,实时查看利息,然后在利息高位及时去下单。

二、环境搭建

详情请看《python爬虫进阶篇:Scrapy中使用Selenium模拟Firefox火狐浏览器爬取网页信息》

三、代码实现

  • items
python">class BondSpiderItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    # 股票代码
    bond_code = scrapy.Field()
    # 股票名称
    bond_name = scrapy.Field()
    # 最新价
    last_price = scrapy.Field()
    # 涨跌幅
    rise_fall_rate = scrapy.Field()
    # 涨跌额
    rise_fall_price = scrapy.Field()
  • middlewares
python">
    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 called

        spider.driver.get(request.url)
        return None
        
    def 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 IgnoreRequest
        response_body = spider.driver.page_source

        return HtmlResponse(url=request.url, body=response_body, encoding='utf-8', request=request)
  • settings设置
python">SPIDER_MIDDLEWARES = {
   'bond_spider.middlewares.BondSpiderSpiderMiddleware': 543,
}
DOWNLOADER_MIDDLEWARES = {
   'bond_spider.middlewares.BondSpiderDownloaderMiddleware': 543,
}
ITEM_PIPELINES = {
   'bond_spider.pipelines.BondSpiderPipeline': 300,
}
  • middlewares中间件
python">from selenium.webdriver.firefox.options import Options as firefox_options


spider.driver = webdriver.Firefox(options=firefox_options())  # 指定使用的浏览器
  • spider文件
python">    def parse(self, response):
        # 股票代码
        bond_code = response.css("table.table_wrapper-table tbody tr td:nth-child(2) a::text").extract()
        # 股票名称
        bond_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(4) 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(5) span::text").extract()

        for i in range(len(bond_code)):
            item = BondSpiderItem()
            item["bond_code"] = bond_code[i]
            item["bond_name"] = bond_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 item

        print()

    def close(self, spider):
        spider.driver.quit()
  • pipelines持久化
python">
    def __init__(self):
        self.html = '<html><head><meta charset="utf-8"></head><body><table>'
        self.html = self.html + '<tr>'
        self.html = self.html + '<td>%s</td>' % "代码"
        self.html = self.html + '<td>%s</td>' % "名称"
        self.html = self.html + '<td>%s</td>' % "最新价"
        self.html = self.html + '<td>%s</td>' % "涨跌幅"
        self.html = self.html + '<td>%s</td>' % "涨跌额"
        self.html = self.html + '</tr>'

    def process_item(self, item, spider):
        self.html = self.html + '<tr>'
        self.html = self.html + '<td>%s</td>' % item["bond_code"]
        self.html = self.html + '<td>%s</td>' % item["bond_name"]
        self.html = self.html + '<td>%s</td>' % item["last_price"]
        self.html = self.html + '<td>%s</td>' % item["rise_fall_rate"]
        self.html = self.html + '<td>%s</td>' % item["rise_fall_price"]
        self.html = self.html + '</tr>'

        return item

    def close_spider(self, spider):
        self.html = self.html + '</table></body></html>'
        self.send_email(self.html)
        print()

    def send_email(self, html):
        # 设置邮箱账号
        account = "xxx"
        # 设置邮箱授权码
        token = "xxx"
        # 实例化smtp对象,设置邮箱服务器,端口
        smtp = smtplib.SMTP_SSL('smtp.qq.com', 465)

        # 登录qq邮箱
        smtp.login(account, token)

        # 添加正文,创建简单邮件对象
        email_content = MIMEText(html, 'html', 'utf-8')

        # 设置发送者信息
        email_content['From'] = 'xxx'
        # 设置接受者信息
        email_content['To'] = '技术总是日积月累的'
        # 设置邮件标题
        email_content['Subject'] = '来自code_space的一封信'

        # 发送邮件
        smtp.sendmail(account, 'xxx', email_content.as_string())
        # 关闭邮箱服务
        smtp.quit()

四、测试结果

在这里插入图片描述


http://www.niftyadmin.cn/n/5286233.html

相关文章

Webpack基础使用

目录 一.什么是Webpack 二.为什么要使用Webpack 三.Webpack的使用 1.下载yarn包管理器 2.Webpack的安装 3.Webpack的简单使用 4.效果 四.Webpack打包流程 一.什么是Webpack Webpack是一个静态模块打包工具 二.为什么要使用Webpack 在开发中&#xff0c;我们常常会遇到…

【SD】通过种子数 差异强度 进行 角色融合【2】

通过 对 2个种子 进行对比 生成 2张图片 风格相符合的图片 best quality,masterpiece,chibi,full body, 我们首先生成1张图 Seed: 726932558 我们再次生成一张图 Seed: 3824894478 随机种子&#xff1a;图一 随机种子&#xff1a;图二 差异强度&#xff1a;0.2 差异强度0.4 差…

Autosar CAN开发03(从实际应用认识CAN总线的物理层)

建议同时阅读本专栏的&#xff1a; Autosar CAN开发03&#xff08;从实际应用认识CAN总线的物理层&#xff09; Autosar CAN开发04&#xff08;从实际应用认识CAN报文&#xff09; Autosar CAN开发05&#xff08;从实际应用认识CAN波特率&#xff09; 前言 在上一章的《AU…

嘭!美国金融巨头 First American 竟遭受黑客攻击

美国第二大保险公司 First American 面临严重的网络攻击 。对此&#xff0c;为了尽量减少此次事件的后果&#xff0c;部分公司系统被禁用&#xff0c;该公司的官方网站也暂时关闭。 First American 成立于 1889 年&#xff0c;专门为房地产行业提供金融和经纪服务。该公司年收入…

OpenAI换血大震动始末:“ChatGPT之父”奥特曼,缘何被“扫地出门”?

近期&#xff0c;AI业界发生了一场“大地震”。作为聊天机器人ChatGPT的开发者&#xff0c;OpenAI无疑是最受关注的人工智能公司之一。就是这家公司的联合创始人、CEO、有“ChatGPT之父”之称的阿尔特曼在“疯狂的5天”里&#xff0c;经历了被闪电免职、加入微软、最终又官复原…

谷歌被曝或再次大裁员!3万员工面临被AI取代

据报道&#xff0c;继1.2万大裁员之后&#xff0c;谷歌又计划重组广告销售部门——这将导致3万名员工面临裁员的风险。 这一年的科技行业&#xff0c;可以说是从年头裁到了年尾&#xff0c;还越裁越多了。 而这次谷歌的部门重组计划&#xff0c;让打工人们发现&#xff0c;除…

kafka发送大消息

1 kafka消息压缩 kafka关于消息压缩的定义&#xff08;来源于官网&#xff09;&#xff1a; 此为 Kafka 中端到端的块压缩功能。如果启用&#xff0c;数据将由 producer 压缩&#xff0c;以压缩格式写入服务器&#xff0c;并由 consumer 解压缩。压缩将提高 consumer 的吞吐量…

day54_echarts

一、Echarts介绍 ECharts是一款基于JavaScript的数据可视化图表库&#xff0c;提供直观&#xff0c;生动&#xff0c;可交互&#xff0c;可个性化定制的数据可视化图表。ECharts最初由百度团队开源&#xff0c;并于2018年初捐赠给Apache基金会&#xff0c;成为ASF孵化级项目。 …