scrapy
БесплатноБез исполняемых скриптовНе проверенScrapy is the standard Python framework for crawling websites and extracting structured data into items, files or databases. Use it when the user asks to…
от TerminalSkills★ 221 звезда на GitHubОб этом скилле
Scrapy — crawl sites and extract structured data in Python
Overview
Scrapy is an asynchronous crawling framework. You write a spider (a class that yields requests and items), Scrapy schedules the requests, respects delays and robots.txt, and passes each item through pipelines to feed exports (JSON, JSON Lines, CSV, XML). It is the right tool for multi-page crawls with link following, retries, throttling and clean separation of fetching, parsing and post-processing. It does not execute JavaScript on its own; for script-rendered pages use a browser-based skill such as playwright, crawlee or crawl4ai instead.
The commands below were run with Scrapy 2.19 against books.toscrape.com, a site built for scraping practice.
Instructions
Installation
Install into a virtual environment, never the system Python:
python3 -m venv .venv
.venv/bin/pip install scrapy
.venv/bin/scrapy version
Scaffold a project
scrapy startproject bookshop
cd bookshop
This creates scrapy.cfg and a bookshop/ package with items.py, middlewares.py, pipelines.py, settings.py and spiders/. The generated settings.py already sets ROBOTSTXT_OBEY = True, DOWNLOAD_DELAY = 1 and CONCURRENT_REQUESTS_PER_DOMAIN = 1. Keep them unless the site owner agrees otherwise.
scrapy genspider books books.toscrape.com writes a spider skeleton in spiders/. Run commands that need the project (crawl, list) from the directory containing scrapy.cfg.
Explore selectors with scrapy shell
Test selectors before writing the spider. -c runs one expression and exits, which suits scripts and agents:
scrapy shell "https://books.toscrape.com/" -c 'response.css("article.product_pod h3 a::attr(title)").getall()[:3]'
Interactively, response, fetch(url) and view(response) are available. Use .get() for the first match (or None) and .getall() for a list. XPath works the same way via response.xpath(...).
Items
Declare the fields in bookshop/items.py:
import scrapy
class BookItem(scrapy.Item):
title = scrapy.Field()
price_gbp = scrapy.Field()
in_stock = scrapy.Field()
rating = scrapy.Field()
url = scrapy.Field()
Plain dicts also work as items; use scrapy.Item when you want typo protection on field names.
A spider that follows pagination
bookshop/spiders/books.py:
import scrapy
from bookshop.items import BookItem
RATINGS = {"One": 1, "Two": 2, "Three": 3, "Four": 4, "Five": 5}
class BooksSpider(scrapy.Spider):
name = "books"
allowed_domains = ["books.toscrape.com"]
start_urls = ["https://books.toscrape.com/catalogue/category/books/mystery_3/index.html"]
def parse(self, response):
for card in response.css("article.product_pod"):
item = BookItem()
item["title"] = card.css("h3 a::attr(title)").get()
item["price_gbp"] = card.css("p.price_color::text").get()
item["in_stock"] = "In stock" in "".join(card.css("p.availability::text").getall())
item["rating"] = RATINGS.get(card.css("p.star-rating::attr(class)").get("").split()[-1])
item["url"] = response.urljoin(card.css("h3 a::attr(href)").get())
yield item
yield from response.follow_all(css="li.next a", callback=self.parse)
start_urls is enough for fixed entry points. When requests need custom headers, POST bodies or computed URLs, define async def start(self) (Scrapy 2.13+) that yields scrapy.Request objects instead. To fetch a detail page per item, yield response.follow(href, callback=self.parse_detail) and pass data along with cb_kwargs={"title": title}.
Clean data in a pipeline
bookshop/pipelines.py:
from scrapy.exceptions import DropItem
class PriceCleanPipeline:
def process_item(self, item):
raw = item.get("price_gbp")
if not raw:
raise DropItem(f"no price on {item.get('url')}")
item["price_gbp"] = float(raw.replace("£", "").replace("Â", ""))
return item
Enable it in settings.py; the number orders pipelines (lower runs first):
ITEM_PIPELINES = {"bookshop.pipelines.PriceCleanPipeline": 300}
The signature is process_item(self, item); older code taking a spider argument is deprecated. Pipelines are also where database inserts and deduplication belong.
Run and export
scrapy list
scrapy crawl books -O books.json
scrapy crawl books -O books.csv
-O overwrites the output file; -o appends, which breaks .json files (use .jsonl when appending). The format comes from the extension. For several outputs or per-feed options, set FEEDS in settings.py:
FEEDS = {
"output/books.jsonl": {"format": "jsonlines", "overwrite": True},
"output/books.csv": {"format": "csv", "overwrite": True},
}
A self-contained single-file spider runs without a project: scrapy runspider myspider.py -O out.json.
Pol
Установить scrapy в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл scrapy?
Scrapy is the standard Python framework for crawling websites and extracting structured data into items, files or databases. Use it when the user asks to "write a Scrapy spider", "crawl a whole site", "follow pagination and export to JSON or CSV", "scrape with CSS selectors", "throttle or obey robots.txt", or "clean scraped items in a pipeline". Covers project scaffolding, spiders, items, pipelines, feed exports, polite-crawl settings and debugging with scrapy shell.
Как установить скилл scrapy?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл scrapy запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic