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

每天一个Python库:Scrapy爬虫,从零搭建数据抓取引擎前言 Scrapy 是啥 Scrapy 是 Python 一个非常强大的爬虫框架 特点是 数据抓取效率极高支持分层设计 代码组织清晰内置队列 内置缓存支持代理 重试 反爬方案一句话 用于构建大规模 高性能爬虫系统的首选框架

欢迎大家来到IT世界,在知识的湖畔探索吧!

☝️前言:Scrapy是啥?

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

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

欢迎大家来到IT世界,在知识的湖畔探索吧!

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

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

Scrapy



欢迎大家来到IT世界,在知识的湖畔探索吧!

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


快速启动Scrapy项目

步骤1:安装Scrapy

欢迎大家来到IT世界,在知识的湖畔探索吧!pip3 install scrapy

步骤2:创建Scrapy项目

scrapy startproject quotesbotcd quotesbot

目录结构:

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

目录结构


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

步骤3:创建spider

欢迎大家来到IT世界,在知识的湖畔探索吧!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下执行

欢迎大家来到IT世界,在知识的湖畔探索吧!scrapy crawl quotes -o quotes.json

输出格式支持

· JSON,CSV,XML

scrapy crawl quotes -o quotes.csv scrapy crawl quotes -o quotes.xml
每天一个Python库:Scrapy爬虫,从零搭建数据抓取引擎

输出格式支持

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

quotes.csv


高阶技巧

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

欢迎大家来到IT世界,在知识的湖畔探索吧!HTTPCACHE_ENABLED = True

2.使用代理IP

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

完整的settings.py

欢迎大家来到IT世界,在知识的湖畔探索吧!# 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合作写入数据库,此处不展开,需要可单独出文。

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

输出到MySQLpandas


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()) 
每天一个Python库:Scrapy爬虫,从零搭建数据抓取引擎

pandas读取数据


实际场景

· 日志自动抓取

· 科研资料批量引用

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

· 网站价格监控


总结

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


下期预告

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

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

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://itzsg.com/134868.html

(0)
上一篇 4天前
下一篇 4天前

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

联系我们YX

mu99908888

在线咨询: 微信交谈

邮件:itzsgw@126.com

工作时间:时刻准备着!

关注微信