python爬虫进阶篇:scrapy爬虫框架的依赖库搭建和项目创建

一、前言

上篇我们记录了Scrapy的各个组件功能,这篇我们来动手scrapy爬虫框架的依赖库搭建和项目创建,开始进入进阶实战。

二、环境搭建

  • 安装依赖库
python 复制代码
pip install lxml==4.9.2
pip install parsel==1.6.0
pip install Twisted==21.2.0
pip install pyOpenSSL==19.1.0
pip install cryptography==2.8
pip install Scrapy==1.6.0

以上依赖库是必须要安装的,否则启动Scrapy会报依赖包不存在的错;Scrapy的依赖包对版本要求比较严格,不同版本的依赖包经常会冲突,上面这些依赖包是测试过没有问题的。

三、创建Scrapy项目

  • 创建一个爬虫项目文件夹scrapy_demo01
  • 命令行进入此文件夹,执行命令:
python 复制代码
scrapy startproject scrapy_demo
  • 将第一层scrapy_demo文件夹设置为根目录(pycharm中右键此文件夹,Mark directory as Sources Root)
  • 创建个spider_main.py文件,用于执行启动爬虫的命令
python 复制代码
from scrapy import cmdline

if __name__ == '__main__':

    cmdline.execute("scrapy crawl demo_spider".split())
  • 最后的项目结构如下

四、测试结果

python 复制代码
# -*- coding: utf-8 -*-
import scrapy

class DemoSpider(scrapy.Spider):
    name = "demo_spider"

    def start_requests(self):
        urls = [
            'http://quotes.toscrape.com/page/1/',
            'http://quotes.toscrape.com/page/2/',
        ]
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        page = response.url.split("/")[-2]
        filename = f'quotes-{page}.html'
        with open(filename, 'wb') as f:
            f.write(response.body)
        self.log(f'Saved file {filename}')

相关推荐
喝茶与编码9 分钟前
Python异步并发控制:asyncio.gather 与 Semaphore 协同设计解析
后端·python
zone773923 分钟前
003:RAG 入门-LangChain 读取图片数据
后端·python·面试
用户83562907805137 分钟前
在 PowerPoint 中用 Python 添加和定制形状的完整教程
后端·python
用户962377954482 小时前
🚀 docx2md-picgo:Word 文档图片一键上传图床工具
python·markdown
zone77391 天前
001:简单 RAG 入门
后端·python·面试
F_Quant1 天前
🚀 Python打包踩坑指南:彻底解决 Nuitka --onefile 配置文件丢失与重启报错问题
python·操作系统
允许部分打工人先富起来1 天前
在node项目中执行python脚本
前端·python·node.js
IVEN_1 天前
Python OpenCV: RGB三色识别的最佳工程实践
python·opencv
haosend1 天前
AI时代,传统网络运维人员的转型指南
python·数据网络·网络自动化
曲幽1 天前
不止于JWT:用FastAPI的Depends实现细粒度权限控制
python·fastapi·web·jwt·rbac·permission·depends·abac