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)

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

相关推荐
随心点儿29 分钟前
使用python 将多个docx文件合并为一个word
开发语言·python·多个word合并为一个
不学无术の码农32 分钟前
《Effective Python》第十三章 测试与调试——使用 Mock 测试具有复杂依赖的代码
开发语言·python
sleepybear111339 分钟前
在Ubuntu上从零开始编译并运行Home Assistant源码并集成HACS与小米开源的Ha Xiaomi Home
python·智能家居·小米·home assistant·米家·ha xiaomi home
纪伊路上盛名在44 分钟前
(鱼书)深度学习入门1:python入门
人工智能·python·深度学习
夏末蝉未鸣011 小时前
python transformers笔记(TrainingArguments类)
python·自然语言处理·transformer
德育处主任Pro1 小时前
「py数据分析」04如何将 Python 爬取的数据保存为 CSV 文件
数据库·python·数据分析
咸鱼鲸1 小时前
【PyTorch】PyTorch中数据准备工作(AI生成)
人工智能·pytorch·python
Python×CATIA工业智造2 小时前
列表页与详情页的智能识别:多维度判定方法与工业级实现
爬虫·深度学习·pycharm
遇见你很高兴2 小时前
Pycharm中体验通义灵码来AI辅助编程
python
大虫小呓2 小时前
50个Python处理Excel示例代码,覆盖95%日常使用场景-全网最全
python·excel