每天一个Python库:Scrapy爬虫,从零搭建数据抓取引擎

前言:Scrapy是啥?

Scrapy 是 Python 一个非常强大的爬虫框架,特点是:

数据抓取效率极高
支持分层设计:代码组织清晰
内置队列、内置缓存
支持代理/重试/反爬方案

一句话:用于构建大规模、高性能爬虫系统的首选框架。

学习本来就不是一蹴而就的事,不过只要你肯练、敢用,坚持,你一定能看到变化!



快速启动Scrapy项目

步骤1:安装Scrapy

pip3 install scrapy

步骤2:创建Scrapy项目

scrapy startproject quotesbotcd quotesbot

目录结构:



实战案例:爬取quotes.toscrape.com

步骤3:创建spider

scrapy genspider quotes quotes.toscrape.com

步骤4:修改spiders/quotes.py

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project :Fish
@File    :D21.py
@Date    :2025/6/22 20:24
@Author : malijie
"""

import scrapy


class QuotesSpider(scrapy.Spider):
    name = "quotes"
    start_urls = ['https://quotes.toscrape.com']

    def parse(self, response):
        for quote in response.css('div.quote'):
            yield {
                'text': quote.css('span.text::text').get(),
                'author': quote.css('small.author::text').get(),
                'tags': quote.css('div.tags a.tag::text').getall(),
            }

步骤5:启动爬虫

在quotesbot下执行

scrapy crawl quotes -o quotes.json

输出格式支持

· JSON,CSV,XML

scrapy crawl quotes -o quotes.csv
scrapy crawl quotes -o quotes.xml



高阶技巧

1.添加缓存:避免重复爬取

HTTPCACHE_ENABLED = True

2.使用代理IP

DOWNLOADER_MIDDLEWARES = {
 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware': 1,
}
HTTP_PROXY = 'http://127.0.0.1:8080'

完整的settings.py

# Scrapy settings for quotesbotcd project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     https://docs.scrapy.org/en/latest/topics/settings.html
#     https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#     https://docs.scrapy.org/en/latest/topics/spider-middleware.html

BOT_NAME = "quotesbotcd"

SPIDER_MODULES = ["quotesbotcd.spiders"]
NEWSPIDER_MODULE = "quotesbotcd.spiders"

ADDONS = {}

# Crawl responsibly by identifying yourself (and your website) on the user-agent
# USER_AGENT = "quotesbotcd (+http://www.yourdomain.com)"

# Obey robots.txt rules
ROBOTSTXT_OBEY = True

# Configure maximum concurrent requests performed by Scrapy (default: 16)
# CONCURRENT_REQUESTS = 32

# Configure a delay for requests for the same website (default: 0)
# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
# DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
# CONCURRENT_REQUESTS_PER_DOMAIN = 16
# CONCURRENT_REQUESTS_PER_IP = 16

# Disable cookies (enabled by default)
# COOKIES_ENABLED = False

# Disable Telnet Console (enabled by default)
# TELNETCONSOLE_ENABLED = False

# Override the default request headers:
# DEFAULT_REQUEST_HEADERS = {
#    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
#    "Accept-Language": "en",
# }

# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
# SPIDER_MIDDLEWARES = {
#    "quotesbotcd.middlewares.QuotesbotcdSpiderMiddleware": 543,
# }

# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html

# 使用代理IP
DOWNLOADER_MIDDLEWARES = {
    'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware': 1,
}
HTTP_PROXY = 'http://127.0.0.1:8080'

# Enable or disable extensions
# See https://docs.scrapy.org/en/latest/topics/extensions.html
# EXTENSIONS = {
#    "scrapy.extensions.telnet.TelnetConsole": None,
# }

# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
   "quotesbotcd.pipelines.MySQLPipeline": 300,
}

# Enable and configure the AutoThrottle extension (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/autothrottle.html
# AUTOTHROTTLE_ENABLED = True
# The initial download delay
# AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
# AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
# AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
# AUTOTHROTTLE_DEBUG = False

# Enable and configure HTTP caching (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings

# 添加缓存:避免重复爬取
HTTPCACHE_ENABLED = True

# HTTPCACHE_EXPIRATION_SECS = 0
# HTTPCACHE_DIR = "httpcache"
# HTTPCACHE_IGNORE_HTTP_CODES = []
# HTTPCACHE_STORAGE = "scrapy.extensions.httpcache.FilesystemCacheStorage"

# Set settings whose default value is deprecated to a future-proof value
FEED_EXPORT_ENCODING = "utf-8"


3.输出到MySQL

使用经典的 pymysql + pipeline合作写入数据库,此处不展开,需要可单独出文。



pandas读取爬取结果效果图

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project :Fish 
@File    :test.py
@Date    :2025/6/22 20:54 
@Author : malijie
"""
import pandas as pd

df = pd.read_json("quotes.json")
print(df.head())



实际场景

· 日志自动抓取

· 科研资料批量引用

· 网站评论/热度数据分析

· 网站价格监控



总结

Scrapy 是开发者和数据分析师的最好助手。开发效率高,解耦功能强,多项爬取一齐管理,能够快速打造一套完整的数据抓取系统。


下期预告

《每天一个 Python 库:httpx 异步请求实战,快速接口体验第一名!》

点赞收藏评论 支持更新,我会续续更新更多实用 Python 库和案例!

原文链接:,转发请注明来源!