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

一、前言

接着上一篇的笔记,Scrapy爬取普通无反爬、静态页面的网页时可以顺利爬取我们要的信息。但是大部分情况下我们要的数据所在的网页它是动态加载出来的(ajax请求后传回前端页面渲染、js调用function等)。这种情况下需要使用selenium进行模拟人工操作浏览器行为,实现自动化采集动态网页数据。

二、环境搭建

  • Scrapy框架的基本依赖包(前几篇有记录)
  • selenium依赖包
    • pip install selenium==4.0.0a6.post2
    • pip install certifi
    • pip install urllib3==1.25.11
  • 安装Firefox浏览器和对应版本的驱动包
    • 火狐浏览器我用的是最新版121.0
    • 驱动的版本为0.3.0,见上方资源链接
    • 把驱动放到python环境的Scripts文件夹下

三、代码实现

  • settings设置
python 复制代码
SPIDER_MIDDLEWARES = {
   'stock_spider.middlewares.StockSpiderSpiderMiddleware': 543,
}

DOWNLOADER_MIDDLEWARES = {
   'stock_spider.middlewares.StockSpiderDownloaderMiddleware': 543,
}

ITEM_PIPELINES = {
   'stock_spider.pipelines.StockSpiderPipeline': 300,
}
  • middlewares中间件
python 复制代码
from selenium.webdriver.firefox.options import Options as firefox_options


spider.driver = webdriver.Firefox(options=firefox_options())  # 指定使用的浏览器
  • process_request
python 复制代码
    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("http://www.baidu.com")
        return None
  • process_response
python 复制代码
	from scrapy.http import HtmlResponse
    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)

启动爬虫后就可以看到爬虫启动了浏览器驱动,接下来就可以实现各种模拟人工操作了

相关推荐
实名上网宋凯宣7 小时前
Django
后端·python·django
如若1238 小时前
【论文复现】CoFailMed:从零复现医学图像分割的共享失败审计,含完整代码流程与科研绘图
人工智能·python
砚底藏山河9 小时前
python量化自定义周期 K 线合成
java·开发语言·数据库·python·金融
视觉小萌新9 小时前
AI Class 3 · Chapter 1:变量、字符串、list/dict、if/for(python学习-小白版-有经验可跳过)
python·学习·list
薛定谔的猫-菜鸟程序员10 小时前
软件架构设计师开发资料大全(从入门到精通)
后端·python·系统架构·flask·架构设计师
Ramble_Naylor12 小时前
Rust深度解读:Send 与 Sync 的本质与线程安全边界
python·算法·rust
Allen_LVyingbo12 小时前
NVIDIA CUDA Tile 在医疗计算中的算子形式化、算法重构与内核实现
大数据·python·算法·重构·知识图谱·健康医疗·数据库架构
云和数据.ChenGuang13 小时前
Python 闭包详解:从原理到实战
linux·开发语言·人工智能·python·kubernetes
我命由我1234514 小时前
Python 实用操作 - 文件操作(打开与关闭文件、读取文件、文件写入)
java·开发语言·前端·javascript·数据库·python·java-ee
青少儿编程课堂14 小时前
蓝桥杯·全国青少年信息素养大赛·电子学会Python/C++考级:倍增法求最近公共祖先LCA解析
c++·python·算法·bfs·信息学竞赛