# Spiders

Spiders are classes that define how a site, or a group of sites, is scraped:
which requests to send, and how to parse their responses to extract data and to
send additional requests.

A crawl goes as follows:

1. Scrapy iterates the `start()` method of the spider to
   get the initial requests. By default, that method yields a
   [`Request`](request-response.md) object for each URL in
   `start_urls`, with `parse()` as
   [callback](request-response.md "Callbacks").
2. Scrapy downloads each request and calls its callback with the resulting
   [`Response`](request-response.md).
3. Callbacks parse the response, typically using [Selectors](selectors.md), and
   return or yield [item objects](items.md) with the extracted data
   and [`Request`](request-response.md) objects to continue the crawl, which go back
   to step 2. See [Callback output](request-response.md).
4. Items go through [item pipelines](item-pipeline.md), and are
   usually stored through [Feed exports](feed-exports.md).

Scrapy includes different spider classes for different purposes, described
below.

## scrapy.Spider

### *class* scrapy.Spider(name: str | None = None, \*\*kwargs: Any)

Base class that any spider must subclass.

It provides a default `start()` implementation that sends
requests based on the `start_urls` class attribute and calls the
`parse()` method for each response.

Like [Scrapy components](components.md), spiders are
[initialized from the crawler](components.md "Initializing from the crawler"), through
`from_crawler()`, and can be [configured through
settings](components.md "Settings"), which they may also override through
`custom_settings` or `update_settings()`.

#### name *: str*

The name of this spider.

Every spider needs one: `Spider` raises `ValueError` on
initialization if it has no name. You usually define it as a class
attribute, but you can also pass it at initialization time instead, e.g.
`CrawlerProcess.crawl(MySpider, name="myspider")` when [running
Scrapy from a script](practices.md "Run Scrapy from a script").

The name is also how Scrapy locates a spider: the default [spider
loader](api.md "SpiderLoader API") indexes the spiders of your project by
name, which is what allows the [`crawl`](commands.md) command to find them, and
the [`runspider`](commands.md) command ignores spider classes that have no name.
Names should hence be unique within a project; the default spider loader
warns about duplicates and keeps only one of the matching spider classes.
Nothing prevents you from running more than one instance of the same
spider, though, and a custom spider loader (see
[`SPIDER_LOADER_CLASS`](settings.md)) may map names to spider classes in a
completely different way.

If the spider scrapes a single domain, a common practice is to name the
spider after that domain, replacing dots with underscores. For example, a
spider that crawls `books.toscrape.com` would often be called
`books_toscrape_com`.

#### allowed_domains *: Collection[str]*

The domains that this spider is allowed to crawl, if any. Requests for
URLs not belonging to the domain names specified in this list (or their
subdomains) won’t be followed if
[`OffsiteMiddleware`](downloader-middleware.md) is
enabled.

> [!WARNING]
> Changed in version 2.18.0: Changes to this attribute during a crawl are now taken into account.

Let’s say your target URL is `https://www.example.com/1.html`, then add
`'example.com'` to the list.

You may modify this attribute while the spider runs, e.g. to allow domains
that you only learn about from an earlier response. The change affects
requests scheduled after it.

#### start_urls *: list[str]*

Start URLs. See `start()`.

#### custom_settings *: dict[str, Any] | None* *= None*

Settings that override the project-wide configuration when running this
spider. It must be defined as a class attribute, since the settings are
updated before instantiation.

See [Built-in settings reference](settings.md) for a list of built-in settings.

> [!NOTE]
> ### See also
> 
> `update_settings()`, a more verbose but
> more flexible alternative, which allows setting values based on other
> settings or on spider attributes, using priorities other than
> `'spider'`, and extending the settings of a base spider class.
> 
> [2. Spider settings](settings.md "2. Spider settings")

#### crawler *: [Crawler](api.md)*

This attribute is set by the `from_crawler()` class
method after initializing the class, and links to the
[`Crawler`](api.md) object to which this spider instance is
bound.

Crawlers encapsulate a lot of components in the project for single-entry
access (such as extensions, middlewares, signal managers, etc). See
[Crawler API](api.md) for details.

#### settings *: [BaseSettings](api.md)*

Configuration for running this spider. See [Settings](settings.md) for
details.

#### logger

Python logger created with the spider’s `name`.

Use it to send log messages. See [Logging from Spiders](logging.md) for
details.

#### state *: dict[str, Any]*

Spider state to persist between batches. See
[Keeping persistent state between batches](jobs.md) for details.

#### *classmethod* update_settings(settings: [BaseSettings](api.md)) → None

Modify *settings*, the settings of the spider.

This method is called during the initialization of a spider instance.
It can add or update the spider’s configuration values. It is a class
method, meaning that it is called on the `Spider` class
and allows all instances of the spider to share the same configuration.

While per-spider settings can be set in `custom_settings`, using
this method allows you to dynamically add, remove or change settings
based on other settings, spider attributes or other factors, and to use
setting priorities other than `'spider'`. Also, it’s easy to extend
this method in a subclass by overriding it, while doing the same with
`custom_settings` can be hard.

For example, suppose a spider needs to modify [`FEEDS`](feed-exports.md):

```python
import scrapy


class MySpider(scrapy.Spider):
    name = "myspider"
    custom_feed = {
        "/home/user/documents/items.json": {
            "format": "json",
            "indent": 4,
        }
    }

    @classmethod
    def update_settings(cls, settings):
        super().update_settings(settings)
        settings.setdefault("FEEDS", {}).update(cls.custom_feed)
```

#### *classmethod* from_crawler(crawler: [Crawler](api.md), \*args: Any, \*\*kwargs: Any) → Self

Return a new spider instance bound to *crawler*.

You probably won’t need to override this directly because the default
implementation acts as a proxy to the `__init__()` method, calling
it with the given arguments *args* and named arguments *kwargs*, which
is how spider arguments reach a spider.

Nonetheless, this method sets the [`crawler`](api.md) and [`settings`](api.md)
attributes in the new instance so they can be accessed later inside the
spider’s code.

The settings in `crawler.settings` can be modified in this method,
which is handy if you want to modify them based on arguments. As a
consequence, these settings aren’t the final values as they can be
modified later by e.g. [add-ons](addons.md). For the same
reason, most of the [`Crawler`](api.md) attributes aren’t
initialized at this point.

The settings are final and those [`Crawler`](api.md)
attributes are initialized by the time the `start()` method runs
and the [`engine_started`](signals.md) signal is sent, which is the earliest
point where your spider code can rely on them.

> [!NOTE]
> ### See also
> 
> [Initializing from the crawler](components.md)

#### *async* start() → AsyncIterator[Any]

Yield the initial [`Request`](request-response.md) objects to send.

> [!WARNING]
> Added in version 2.13.

For example:

```python
from scrapy import Request, Spider


class MySpider(Spider):
    name = "myspider"

    async def start(self):
        yield Request("https://toscrape.com/")
```

The default implementation reads URLs from `start_urls` and
yields a request for each with [`dont_filter`](request-response.md)
enabled. It is functionally equivalent to:

```python
async def start(self):
    for url in self.start_urls:
        yield Request(url, dont_filter=True)
```

You can also yield [items](items.md). For example:

```python
async def start(self):
    yield {"foo": "bar"}
```

To write spiders that work on Scrapy versions lower than 2.13,
define also a synchronous `start_requests()` method that returns an
iterable. For example:

```python
def start_requests(self):
    yield Request("https://toscrape.com/")
```

> [!NOTE]
> ### See also
> 
> Start requests

#### parse(response: [Response](request-response.md), \*\*kwargs: Any) → Any

Process *response*, i.e. extract data from it and generate new
requests.

This is the default [callback](request-response.md "Callbacks"): Scrapy uses
it for the response to any request that does not define a
[`callback`](request-response.md), such as the requests that
`start()` yields by default.

Any [`cb_kwargs`](request-response.md) of the request are passed as
keyword parameters.

Spiders must define this method, unless every request that they
send defines a callback.

See [Callback output](request-response.md) about the supported return values.

#### closed(reason)

Called when the spider closes. This method provides a shortcut to
signals.connect() for the [`spider_closed`](signals.md) signal.

Let’s see an example:

```python
import scrapy


class MySpider(scrapy.Spider):
    name = "example.com"
    allowed_domains = ["example.com"]
    start_urls = [
        "http://www.example.com/1.html",
        "http://www.example.com/2.html",
        "http://www.example.com/3.html",
    ]

    def parse(self, response):
        self.logger.info("A response from %s just arrived!", response.url)
```

Return multiple Requests and items from a single callback:

```python
import scrapy


class MySpider(scrapy.Spider):
    name = "example.com"
    allowed_domains = ["example.com"]
    start_urls = [
        "http://www.example.com/1.html",
        "http://www.example.com/2.html",
        "http://www.example.com/3.html",
    ]

    def parse(self, response):
        for h3 in response.xpath("//h3").getall():
            yield {"title": h3}

        for href in response.xpath("//a/@href").getall():
            yield scrapy.Request(response.urljoin(href), self.parse)
```

Instead of `start_urls` you can use `start()`
directly; to give data more structure you can use [`Item`](items.md)
objects:

```python
import scrapy
from myproject.items import MyItem


class MySpider(scrapy.Spider):
    name = "example.com"
    allowed_domains = ["example.com"]

    async def start(self):
        yield scrapy.Request("http://www.example.com/1.html", self.parse)
        yield scrapy.Request("http://www.example.com/2.html", self.parse)
        yield scrapy.Request("http://www.example.com/3.html", self.parse)

    def parse(self, response):
        for h3 in response.xpath("//h3").getall():
            yield MyItem(title=h3)

        for href in response.xpath("//a/@href").getall():
            yield scrapy.Request(response.urljoin(href), self.parse)
```

## Spider arguments

Spiders can receive arguments that modify their behaviour. Some common uses for
spider arguments are to define the start URLs or to restrict the crawl to
certain sections of the site, but they can be used to configure any
functionality of the spider.

Spider arguments are passed through the [`crawl`](commands.md) command using the
`-a` option. For example:

```
scrapy crawl myspider -a category=electronics
```

Spiders can access arguments in their \_\_init_\_ methods:

```python
import scrapy


class MySpider(scrapy.Spider):
    name = "myspider"

    def __init__(self, category=None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.start_urls = [f"http://www.example.com/categories/{category}"]
        # ...
```

The default `__init__` method will take any spider arguments and copy them to
the spider as attributes. The above example can also be written as follows:

```python
import scrapy


class MySpider(scrapy.Spider):
    name = "myspider"

    async def start(self):
        yield scrapy.Request(f"http://www.example.com/categories/{self.category}")
```

If you are [running Scrapy from a script](practices.md "Run Scrapy from a script"), you can
specify spider arguments when calling
[`CrawlerProcess.crawl`](api.md) or
[`CrawlerRunner.crawl`](api.md):

```python
process = CrawlerProcess()
process.crawl(MySpider, category="electronics")
```

Keep in mind that spider arguments are only strings. The spider will not do any
parsing on its own. If you were to set the `start_urls` attribute from the
command line, you would have to parse it on your own into a list using
something like [`ast.literal_eval()`](https://docs.python.org/3/library/ast.html#ast.literal_eval) or [`json.loads()`](https://docs.python.org/3/library/json.html#json.loads) and then set it
as an attribute. Otherwise, you would cause iteration over a `start_urls`
string (a very common Python pitfall) resulting in each character being seen as
a separate url.

Spider arguments can also be passed through the Scrapyd `schedule.json` API.
See [Scrapyd documentation](https://scrapyd.readthedocs.io/en/latest/).

### scrapy-spider-metadata parameters

Another alternative to pass spider arguments is the library [scrapy-spider-metadata](https://scrapy-spider-metadata.readthedocs.io/en/latest/params.html).

This allows for Scrapy spiders to define, validate, document and pre-process
their arguments as Pydantic models.

The example shows how to define typed parameters where a string argument
is automatically converted to an integer:

```python
import scrapy
from pydantic import BaseModel
from scrapy_spider_metadata import Args


class MyParams(BaseModel):
    pages: int


class BookSpider(Args[MyParams], scrapy.Spider):
    name = "bookspider"
    start_urls = ["http://books.toscrape.com/catalogue"]

    async def start(self):
        for start_url in self.start_urls:
            for index in range(1, self.args.pages + 1):
                yield scrapy.Request(f"{start_url}/page-{index}.html")

    def parse(self, response):
        book_links = response.css("article.product_pod h3 a::attr(href)").getall()
        for book_link in book_links:
            yield response.follow(book_link, self.parse_book)

    def parse_book(self, response):
        yield {
            "title": response.css("h1::text").get(),
            "price": response.css("p.price_color::text").get(),
        }
```

This spider can be called from the command line:

```
scrapy crawl bookspider -a pages=2
```

## Start requests

**Start requests** are [`Request`](request-response.md) objects yielded from the
`start()` method of a spider or from the
[`process_start()`](spider-middleware.md) method of a
[spider middleware](spider-middleware.md).

> [!NOTE]
> ### See also
> 
> [Start request order](scheduler.md)

### Delaying start request iteration

Scrapy iterates `start()` as fast as it yields, so all start
requests reach the scheduler early in the crawl, however many they are. To
minimize the number of requests in the scheduler at any given time, and with it
resource usage (memory, or disk when using [`JOBDIR`](settings.md)), override
`start()` to pause its iteration whenever there are
scheduled requests:

```python
async def start(self):
    async for item_or_request in super().start():
        if self.crawler.engine.needs_backout():
            await self.crawler.signals.wait_for(signals.scheduler_empty)
        yield item_or_request
```

### Handling start errors

An exception raised by `start()` ends its iteration, so any
remaining start items and requests are never sent. Scrapy logs the exception,
sends the [`spider_error`](signals.md) signal, and, once the already scheduled
requests are done, closes the spider with the `start_error`
[`finish_reason`](stats.md).

> [!WARNING]
> Changed in version 2.18.0: The close reason used to be `finished`, and neither the
> [`spider_error`](signals.md) signal nor the [`spider_exceptions/count`](stats.md) stat
> reported the exception.

To keep the iteration going, catch the exception yourself:

```python
async def start(self):
    for url in self.start_urls:
        try:
            request = Request(url)
        except ValueError:
            self.logger.exception(f"Skipping start URL {url}")
        else:
            yield request
```

To stop the crawl instead, and choose your own [`finish_reason`](stats.md), raise
[`CloseSpider`](exceptions.md).

## Generic Spiders

Scrapy comes with some useful generic spiders that you can use to subclass
your spiders from. Their aim is to provide convenient functionality for a few
common scraping cases, like following all links on a site based on certain
rules, crawling from [Sitemaps](https://www.sitemaps.org/index.html), or parsing an XML/CSV feed.

For the examples used in the following spiders, we’ll assume you have a project
with a `TestItem` declared in a `myproject.items` module:

```python
from dataclasses import dataclass


@dataclass
class TestItem:
    id: str | None = None
    name: str | None = None
    description: str | None = None
```

### CrawlSpider

### *class* scrapy.spiders.CrawlSpider(\*a: Any, \*\*kw: Any)

Spider that follows links based on a set of rules.

You declare a set of `Rule` objects in `rules`, and this
spider extracts links from every response it gets and follows them
accordingly.

Use it only for crawls that fit that declarative model. As soon as you need
to control which requests are sent, in which order, or which data they
carry along, subclass `Spider` instead and follow links from
your callbacks, e.g. with [`response.follow`](request-response.md). That is usually simpler than bending
`rules` to a use case they do not cover.

> [!WARNING]
> Unlike in other spiders, a request without a callback is not
> handled by `Spider.parse`. It is handled by
> `parse_start_url()`, and its links are followed according to
> `rules`.
> 
> That is the way to feed a response of your own to `rules`. If you
> want your own parsing code to run for it instead, set its callback
> explicitly; defining `parse()` is not enough.
> 
> Requests generated from `rules` are not affected, they always get
> a callback of their own.

Requests generated from `rules` carry the index of the matching rule
within `rules` in their `rule` [`Request.meta`](request-response.md) key. `CrawlSpider` needs that key to dispatch
the response to the right rule, so copying it into a request generated by a
different rule sends the response to the wrong callback.

#### rules *: Sequence[Rule]* *= ()*

The rules that define how to crawl the site. If multiple rules match the
same link, the first one will be used, according to the order they’re
defined in this attribute.

#### parse_start_url(response: [Response](request-response.md), \*\*kwargs: Any) → Any

Handle *response*, one of the responses produced for the URLs in the
`start_urls` attribute of the spider.

This is a `spider callback`; override it to
parse the initial responses.

#### Crawling rules

### *class* scrapy.spiders.Rule(link_extractor: LinkExtractor | None = None, callback: CallbackT | str | None = None, cb_kwargs: dict[str, Any] | None = None, follow: bool | None = None, process_links: ProcessLinksT | str | None = None, process_request: ProcessRequestT | str | None = None, errback: Callable[[Failure], Any] | str | None = None, name: str | None = None, from_rules: Iterable[str] | str | None = None)

A link-following rule for `CrawlSpider`, to be used in its
`rules` attribute.

It defines which links to extract from a response, what to do with the
responses those links produce, and whether to keep extracting links from
them.

> [!WARNING]
> Added in version 2.20.0: The *name* and *from_rules* parameters.

> [!WARNING]
> Changed in version 2.20.0: *errback* may now be a coroutine function (`async def`) or an
> asynchronous generator function.

*callback*, *process_links*, *process_request* and *errback* may be
specified as a string instead of a callable, in which case the spider
method with that name is used.

*link_extractor* is a [`LinkExtractor`](link-extractors.md) object which defines
how links will be extracted from each crawled page. Each produced link will
be used to generate a [`Request`](request-response.md) object, which will contain
the link’s text in its `meta` dictionary (under the `link_text` key).
If omitted, a default link extractor created with no arguments will be
used, resulting in all links being extracted.

*callback* is called for each link extracted with *link_extractor*. It is a
`spider callback`. If omitted, no callback runs
for the matching responses, which are then only used to extract further
links, as per *follow*.

*cb_kwargs* are the keyword arguments to pass to the callback.

*follow* determines whether links should be followed from each response
extracted with this rule. It defaults to `True` if *callback* is
`None`, and to `False` otherwise.

*process_links* is called for each list of links extracted from each
response using *link_extractor*. This is mainly used for filtering
purposes.

*process_request* is called for every [`Request`](request-response.md) extracted by
this rule. It should take said request as first argument and the
[`Response`](request-response.md) from which the request originated as second
argument. It must return a [`Request`](request-response.md) object or `None` (to
filter out the request).

Use *process_request* to set the [`priority`](request-response.md) of
requests generated by a rule, e.g. `process_request=lambda request,
response: request.replace(priority=10)`.

*errback* is called if any exception is raised while processing a request
generated by the rule. It receives a
[`Twisted Failure`](https://docs.twisted.org/en/stable/api/twisted.python.failure.Failure.html) instance as first
parameter.

*name* identifies the rule, to be used as a target of the *from_rules* of
other rules.

*from_rules* is the *name* of another rule, or an iterable of names. If
set, this rule is only applied to responses reached through one of those
rules, instead of to every response.

#### CrawlSpider example

Let’s now take a look at an example CrawlSpider with rules:

```python
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor


class MySpider(CrawlSpider):
    name = "example.com"
    allowed_domains = ["example.com"]
    start_urls = ["http://www.example.com"]

    rules = (
        # Extract links matching 'category.php' (but not matching 'subsection.php')
        # and follow links from them (since no callback means follow=True by default).
        Rule(LinkExtractor(allow=(r"category\.php",), deny=(r"subsection\.php",))),
        # Extract links matching 'item.php' and parse them with the spider's method parse_item
        Rule(LinkExtractor(allow=(r"item\.php",)), callback="parse_item"),
    )

    def parse_item(self, response):
        self.logger.info("Hi, this is an item page! %s", response.url)
        item = {}
        item["id"] = response.xpath('//td[@id="item_id"]/text()').re(r"ID: (\d+)")
        item["name"] = response.xpath('//td[@id="item_name"]/text()').get()
        item["description"] = response.xpath(
            '//td[@id="item_description"]/text()'
        ).get()
        item["link_text"] = response.meta["link_text"]
        url = response.xpath('//td[@id="additional_data"]/@href').get()
        return response.follow(
            url, self.parse_additional_page, cb_kwargs=dict(item=item)
        )

    def parse_additional_page(self, response, item):
        item["additional_data"] = response.xpath(
            '//p[@id="additional_data"]/text()'
        ).get()
        return item
```

This spider would start crawling example.com’s home page, collecting category
links, and item links, parsing the latter with the `parse_item` method. For
each item response, some data will be extracted from the HTML using XPath, and
a dictionary will be filled with it.

### XMLFeedSpider

### *class* scrapy.spiders.XMLFeedSpider(name: str | None = None, \*\*kwargs: Any)

Spider for parsing XML feeds by iterating through them by a certain node
name.

The iterator can be chosen from: `iternodes`, `xml`, and `html`. It’s
recommended to use the `iternodes` iterator for performance reasons, since
the `xml` and `html` iterators generate the whole DOM at once in order to
parse it. However, using `html` as the iterator may be useful when parsing
XML with bad markup.

To set the iterator and the tag name, you must define the `iterator`
and `itertag` class attributes.

> [!WARNING]
> Unlike in other spiders, a request without a callback is not
> handled by `Spider.parse`. Its response is
> parsed as an XML feed, calling `parse_node()` for each matching node.
> 
> That is the way to have an additional feed parsed as such. If you want
> your own parsing code to run for it instead, set its callback explicitly;
> defining `parse()` is not enough.

#### iterator *: Literal['iternodes', 'html', 'xml']* *= 'iternodes'*

The iterator to use. It can be either:

- `'iternodes'` - a fast iterator based on `lxml`
- `'html'` - an iterator which uses [`Selector`](selectors.md). Keep in
  mind this uses DOM parsing and must load all DOM in memory which could
  be a problem for big feeds. It also parses the feed with an HTML
  parser, which can silently mangle tags that HTML treats as void
  elements, such as `<link>`, dropping their content and closing tag.
  Use `xml` or `iternodes` instead for feeds affected by this.
- `'xml'` - an iterator which uses [`Selector`](selectors.md). Keep in
  mind this uses DOM parsing and must load all DOM in memory which could
  be a problem for big feeds

#### itertag *: str* *= 'item'*

Name of the node (or element) to iterate in. Example:

```python
itertag = "product"
```

#### namespaces *: Sequence[tuple[str, str]]* *= ()*

`(prefix, uri)` tuples defining the namespaces available in that
document that will be processed with this spider. The `prefix` and
`uri` will be used to automatically register namespaces using the
[`register_namespace()`](selectors.md) method.

You can then specify nodes with namespaces in the `itertag`
attribute.

Example:

```python
from scrapy.spiders import XMLFeedSpider


class YourSpider(XMLFeedSpider):

    namespaces = [("n", "http://www.sitemaps.org/schemas/sitemap/0.9")]
    itertag = "n:url"
    # ...
```

#### process_results(response: [Response](request-response.md), results: Iterable[Any]) → Iterable[Any]

Handle *results*, the items and requests returned by the spider for
*response*, and return them, either unmodified or with changes.

Override it to perform any last-time processing required before
returning the results to the framework core, for example setting the
item IDs.

#### adapt_response(response: [Response](request-response.md)) → [Response](request-response.md)

Handle *response* as soon as it arrives from the spider middleware,
before the spider starts parsing it, and return a response, which can be
the same one or a different one.

Override it to make any changes you want to the feed before parsing it,
e.g. to its body.

#### parse_node(response: [Response](request-response.md), selector: [Selector](selectors.md)) → Any

Handle a node of *response* matching `itertag`, for which
*selector* is a [`Selector`](selectors.md).

This is a `spider callback`. Overriding it
is mandatory. Otherwise, your spider won’t work.

#### XMLFeedSpider example

These spiders are pretty easy to use, let’s have a look at one example:

```python
from scrapy.spiders import XMLFeedSpider
from myproject.items import TestItem


class MySpider(XMLFeedSpider):
    name = "example.com"
    allowed_domains = ["example.com"]
    start_urls = ["http://www.example.com/feed.xml"]
    iterator = "iternodes"  # This is actually unnecessary, since it's the default value
    itertag = "item"

    def parse_node(self, response, node):
        self.logger.info(
            "Hi, this is a <%s> node!: %s", self.itertag, "".join(node.getall())
        )

        item = TestItem()
        item.id = node.xpath("@id").get()
        item.name = node.xpath("name").get()
        item.description = node.xpath("description").get()
        return item
```

Basically what we did up there was to create a spider that downloads a feed from
the given `start_urls`, and then iterates through each of its `item` tags,
prints them out, and stores some random data in an [`Item`](items.md).

### CSVFeedSpider

### *class* scrapy.spiders.CSVFeedSpider(name: str | None = None, \*\*kwargs: Any)

Spider for parsing CSV feeds.

This spider is very similar to `XMLFeedSpider`, except that it
iterates over rows, instead of nodes. The method that gets called in each
iteration is `parse_row()`.

> [!WARNING]
> Unlike in other spiders, a request without a callback is not
> handled by `Spider.parse`. Its response is
> parsed as a CSV feed, calling `parse_row()` for each row.
> 
> That is the way to have an additional feed parsed as such. If you want
> your own parsing code to run for it instead, set its callback explicitly;
> defining `parse()` is not enough.

#### delimiter *: str | None* *= None*

Separator character for each field in the CSV file.

`None` means using the default delimiter of the [`csv`](https://docs.python.org/3/library/csv.html#module-csv) module,
`','` (comma).

#### quotechar *: str | None* *= None*

Enclosure character for each field in the CSV file.

`None` means using the default quote character of the [`csv`](https://docs.python.org/3/library/csv.html#module-csv) module,
`'"'` (quotation mark).

#### headers *: list[str] | None* *= None*

Column names in the CSV file.

#### process_results(response: [Response](request-response.md), results: Iterable[Any]) → Iterable[Any]

Same as `XMLFeedSpider.process_results()`.

#### adapt_response(response: [Response](request-response.md)) → [Response](request-response.md)

Same as `XMLFeedSpider.adapt_response()`.

#### parse_row(response: [Response](request-response.md), row: dict[str, str]) → Any

Handle *row*, a row of *response* as a dict with a key for each
provided (or detected) header of the CSV file.

This is a `spider callback`. Overriding it
is mandatory. Otherwise, your spider won’t work.

#### CSVFeedSpider example

Let’s see an example similar to the previous one, but using a
`CSVFeedSpider`:

```python
from scrapy.spiders import CSVFeedSpider
from myproject.items import TestItem


class MySpider(CSVFeedSpider):
    name = "example.com"
    allowed_domains = ["example.com"]
    start_urls = ["http://www.example.com/feed.csv"]
    delimiter = ";"
    quotechar = "'"
    headers = ["id", "name", "description"]

    def parse_row(self, response, row):
        self.logger.info("Hi, this is a row!: %r", row)

        item = TestItem()
        item.id = row["id"]
        item.name = row["name"]
        item.description = row["description"]
        return item
```

### SitemapSpider

### *class* scrapy.spiders.SitemapSpider(\*a: Any, \*\*kw: Any)

Spider that crawls a site by discovering its URLs using [sitemaps](https://www.sitemaps.org/index.html).

It supports nested sitemaps and discovering sitemap URLs from [robots.txt](https://www.robotstxt.org/).

#### sitemap_urls *: Sequence[str]* *= ()*

URLs pointing to the sitemaps whose URLs you want to crawl.

You can also point to a [robots.txt](https://www.robotstxt.org/) and it
will be parsed to extract sitemap URLs from it.

#### sitemap_rules *: Sequence[tuple[re.Pattern[str] | str, str | CallbackT]]* *= [('', 'parse')]*

`(regex, callback)` tuples where:

- `regex` is a regular expression to match URLs extracted from
  sitemaps. `regex` can be either a str or a compiled regex object.
- `callback` is the callback to use for processing the URLs that match
  the regular expression. `callback` can be a string (indicating the
  name of a spider method) or a callable.

For example:

```python
sitemap_rules = [("/product/", "parse_product")]
```

Rules are applied in order, and only the first one that matches will be
used.

The default value makes all URLs found in sitemaps be processed with the
`parse()` callback.

#### sitemap_follow *: Sequence[re.Pattern[str] | str]* *= ['']*

Regexes of sitemap URLs that should be followed: those linked from
[sitemap index files](https://www.sitemaps.org/protocol.html#index), and
those declared through the `Sitemap` directive of a `robots.txt`
file.

By default, all sitemaps are followed.

#### sitemap_alternate_links *: bool* *= False*

Specifies if alternate links for one `url` should be followed. These are
links for the same website in another language passed within the same
`url` block.

For example:

```xml
<url>
    <loc>http://example.com/</loc>
    <xhtml:link rel="alternate" hreflang="de" href="http://example.com/de"/>
</url>
```

When enabled, this would retrieve both URLs. When disabled, only
`http://example.com/` would be retrieved.

#### sitemap_schemes *: Sequence[str] | None* *= None*

URL schemes that the URLs found in sitemaps and `robots.txt` files
may use.

> [!WARNING]
> Added in version 2.20.0.

If `None`, they may only use `http`, `https` or the scheme of the
sitemap or `robots.txt` file they come from. Use `()` to follow
URLs regardless of their scheme.

#### sitemap_filter(entries: Iterable[dict[str, Any]]) → Iterable[dict[str, Any]]

Yield the sitemap entries from *entries* that should be processed.

Override it to select sitemap entries based on their attributes. For
example, given the following sitemap entry:

```xml
<url>
    <loc>http://example.com/</loc>
    <lastmod>2005-01-01</lastmod>
</url>
```

You can filter entries by date as follows:

```python
from datetime import datetime
from scrapy.spiders import SitemapSpider


class FilteredSitemapSpider(SitemapSpider):
    name = "filtered_sitemap_spider"
    allowed_domains = ["example.com"]
    sitemap_urls = ["http://example.com/sitemap.xml"]

    def sitemap_filter(self, entries):
        for entry in entries:
            date_time = datetime.strptime(entry["lastmod"], "%Y-%m-%d")
            if date_time.year >= 2005:
                yield entry
```

This would retrieve only entries modified on 2005 and the following
years.

Entries are dict objects extracted from the sitemap document. Usually,
the key is the tag name and the value is the text inside it.

It’s important to notice that:

- as the `loc` attribute is required, entries without this tag are
  discarded
- alternate links are stored in a list with the key `alternate`
  (see `sitemap_alternate_links`)
- namespaces are removed, so lxml tags named as `{namespace}tagname`
  become only `tagname`

The default implementation yields all entries, observing other
attributes and their settings.

#### sitemap_request(loc: str, callback: CallbackT, entry: dict[str, Any], \*, source: Literal['robotstxt', 'sitemapindex', 'urlset'], response: [Response](request-response.md)) → [Request](request-response.md)

Return the request for the *loc* URL of the sitemap *entry*, to be
parsed with *callback*.

> [!WARNING]
> Added in version 2.20.0.

Override this method to build those requests differently, e.g. to
carry sitemap data and request metadata over to *callback*:

```python
def sitemap_request(self, loc, callback, entry, *, source, response):
    meta = {
        "lastmod": entry.get("lastmod"),
        "site": response.meta.get("site"),
    }
    return Request(loc, callback, meta=meta)
```

*entry* is the sitemap entry that *loc* comes from, as described in
`sitemap_filter()`. When `sitemap_alternate_links` is
enabled, the same entry is used for every alternate URL.

*source* tells where *loc* comes from: `"urlset"` for a URL to
crawl, `"sitemapindex"` for a sitemap linked from a sitemap index,
and `"robotstxt"` for a sitemap linked from a `robots.txt`
file, where *entry* only has `loc`.

*response* is the response that *entry* was read from.

#### SitemapSpider examples

Simplest example: process all urls discovered through sitemaps using the
`parse` callback:

```python
from scrapy.spiders import SitemapSpider


class MySpider(SitemapSpider):
    sitemap_urls = ["http://www.example.com/sitemap.xml"]

    def parse(self, response):
        pass  # ... scrape item here ...
```

Process some urls with certain callback and other urls with a different
callback:

```python
from scrapy.spiders import SitemapSpider


class MySpider(SitemapSpider):
    sitemap_urls = ["http://www.example.com/sitemap.xml"]
    sitemap_rules = [
        ("/product/", "parse_product"),
        ("/category/", "parse_category"),
    ]

    def parse_product(self, response):
        pass  # ... scrape product ...

    def parse_category(self, response):
        pass  # ... scrape category ...
```

Follow sitemaps defined in the [robots.txt](https://www.robotstxt.org/) file and only follow sitemaps
whose url contains `/sitemap_shop`:

```python
from scrapy.spiders import SitemapSpider


class MySpider(SitemapSpider):
    sitemap_urls = ["http://www.example.com/robots.txt"]
    sitemap_rules = [
        ("/shop/", "parse_shop"),
    ]
    sitemap_follow = ["/sitemap_shops"]

    def parse_shop(self, response):
        pass  # ... scrape shop here ...
```

Combine SitemapSpider with other sources of urls:

```python
from scrapy import Request
from scrapy.spiders import SitemapSpider


class MySpider(SitemapSpider):
    sitemap_urls = ["http://www.example.com/robots.txt"]
    sitemap_rules = [
        ("/shop/", "parse_shop"),
    ]

    other_urls = ["http://www.example.com/about"]

    async def start(self):
        async for item_or_request in super().start():
            yield item_or_request
        for url in self.other_urls:
            yield Request(url, self.parse_other)

    def parse_shop(self, response):
        pass  # ... scrape shop here ...

    def parse_other(self, response):
        pass  # ... scrape other here ...
```
