Scrapy 教程
1. 框架定位
Section titled “1. 框架定位”Scrapy 是一个为了爬取网站数据、提取结构性数据而编写的开源应用框架。它底层基于 Twisted 异步网络库,拥有极高的抓取并发能力,适用于构建复杂的爬虫体系和分布式数据采集系统。
(安装依赖:pip install scrapy)
2. 模式 A:轻量级单文件脚本
Section titled “2. 模式 A:轻量级单文件脚本”适用于简单的、无需复杂管道 (Pipeline) 处理的临时抓取任务。
quotes_spider.py 示例:
import scrapy
class QuotesSpider(scrapy.Spider): name = "quotes" # 框架默认入口,自动下发 GET 请求并进入 parse 回调 start_urls = [ "https://quotes.toscrape.com/tag/humor/", ]
def parse(self, response): # 1. 业务抽取:使用内置的 CSS / XPath 选择器提炼数据 for quote in response.css("div.quote"): yield { "author": quote.xpath("span/small/text()").get(), "text": quote.css("span.text::text").get(), }
# 2. 翻页爬取:提取下一页链接,并自动推入调度队列 next_page = response.css('li.next a::attr("href")').get() if next_page is not None: yield response.follow(next_page, self.parse)终端执行并直接序列化落盘:
scrapy runspider quotes_spider.py -o quotes.jsonl3. 模式 B:标准工程化脚手架
Section titled “3. 模式 B:标准工程化脚手架”适用于复杂的大型抓取任务,需配置防封禁(Downloader Middleware)、自动存库(Pipeline)等高阶行为。
3.1. 初始化框架
Section titled “3.1. 初始化框架”scrapy startproject quotes_democd quotes_demo3.2. 编写独立 Spider (spiders/quotes_spider.py)
Section titled “3.2. 编写独立 Spider (spiders/quotes_spider.py)”演示如何手动控制初始请求的分发,以及将抓取的原始 HTML 落地。
from pathlib import Pathimport scrapy
class QuotesSpider(scrapy.Spider): name = "quotes"
def start_requests(self): """覆盖默认的 start_urls,支持灵活定制初始 headers 或 payload""" urls = [ "https://quotes.toscrape.com/page/1/", "https://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" Path(filename).write_bytes(response.body) self.log(f"Saved file {filename}")3.3. 运行工程级爬虫
Section titled “3.3. 运行工程级爬虫”# 执行名为 quotes 的爬虫任务scrapy crawl quotes4. 高阶调试神器:Scrapy Shell
Section titled “4. 高阶调试神器:Scrapy Shell”在编写解析逻辑前,强烈建议使用框架提供的 Shell 终端进行实时调试。它会自动拉取页面,并把你直接放置在交互式环境中:
scrapy shell 'https://quotes.toscrape.com/page/1/'
# 进入交互式终端后,可直接测试选择器:# >>> response.css('span.text:: text').getall()# >>> quit()5. 拓展生态
Section titled “5. 拓展生态”- 动态页面内容抓取:原生的 Scrapy 无法执行 JS 渲染。遇到 React/Vue 单页应用时,必须借助
Splash中间件,或直接挂载Playwright/Selenium。