<a id="topics-request-response"></a>

# Requests and Responses

Scrapy uses [`Request`](#scrapy.Request) and [`Response`](#scrapy.http.Response) objects for crawling web
sites.

Typically, [`Request`](#scrapy.Request) objects are generated in the spiders and pass
across the system until they reach the Downloader, which executes the request
and returns a [`Response`](#scrapy.http.Response) object which travels back to the spider that
issued the request.

Both [`Request`](#scrapy.Request) and [`Response`](#scrapy.http.Response) classes have subclasses which add
functionality not required in the base classes. These are described
below in [Request subclasses](#topics-request-response-ref-request-subclasses) and
[Response subclasses](#topics-request-response-ref-response-subclasses).

## Request objects

### *class* scrapy.Request(\*args: Any, \*\*kwargs: Any)

Represents an HTTP request, which is usually generated in a Spider and
executed by the Downloader, thus generating a [`Response`](#scrapy.http.Response).

* **Parameters:**
  * **url** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) – 

    the URL of this request

    If the URL is invalid, a [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) exception is raised.
  * **callback** (*Callable* *[**Concatenate* *[*[*Response*](#scrapy.http.Response) *,*  *...* *]* *,* *Any* *]*  *|* *None*) – sets [`callback`](#scrapy.Request.callback), defaults to `None`.
  * **method** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) – the HTTP method of this request. Defaults to `'GET'`.
  * **meta** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict)) – the initial values for the [`Request.meta`](#scrapy.Request.meta) attribute. If
    given, the dict passed in this parameter will be shallow copied.
  * **body** ([*bytes*](https://docs.python.org/3/library/stdtypes.html#bytes) *or* [*str*](https://docs.python.org/3/library/stdtypes.html#str)) – the request body. If a string is passed, then it’s encoded as
    bytes using the `encoding` passed (which defaults to `utf-8`). If
    `body` is not given, an empty bytes object is stored. Regardless of the
    type of this argument, the final value stored will be a bytes object
    (never a string or `None`).
  * **headers** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict)) – 

    the headers of this request. The dict values can be strings
    (for single valued headers) or lists (for multi-valued headers). If
    `None` is passed as value, the HTTP header will not be sent at all.
    > [!CAUTION]
    > Cookies set via the `Cookie` header are not considered by the
    > [cookie middleware](cookies.md#cookies). If you need to set cookies for a
    > request, use the `cookies` argument.
  * **cookies** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict) *or* [*list*](https://docs.python.org/3/library/stdtypes.html#list)) – the request cookies, as a dict of cookie names and values
    or as a list of dicts with a cookie each. See [Cookies](cookies.md#cookies).
  * **encoding** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) – 

    the encoding of this request (defaults to `'utf-8'`).
    This encoding will be used to percent-encode the URL and to convert the
    body to bytes (if given as a string).

    To disable URL percent-encoding for a request, use the
    [`verbatim_url`](#std-reqmeta-verbatim_url) request meta key.
  * **priority** ([*int*](https://docs.python.org/3/library/functions.html#int)) – sets [`priority`](#scrapy.Request.priority), defaults to `0`.
  * **dont_filter** ([*bool*](https://docs.python.org/3/library/functions.html#bool)) – sets [`dont_filter`](#scrapy.Request.dont_filter), defaults to `False`.
  * **errback** (*Callable* *[* *[**Failure* *]* *,* *Any* *]*  *|* *None*) – sets [`errback`](#scrapy.Request.errback), defaults to `None`.
  * **flags** ([*list*](https://docs.python.org/3/library/stdtypes.html#list)) – Flags sent to the request, can be used for logging or similar purposes.
  * **cb_kwargs** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict)) – A dict with arbitrary data that will be passed as keyword arguments to the Request’s callback.

#### url

A string containing the URL of this request.

Keep in mind that this attribute contains the escaped URL, so it can
differ from the URL passed in the `__init__()` method.

If [`verbatim_url`](#std-reqmeta-verbatim_url) is set to `True`, the URL is kept as
passed to `__init__()`.

This attribute is read-only. To change the URL of a Request use
[`replace()`](#scrapy.Request.replace).

#### method

A string representing the HTTP method in the request. This is guaranteed to
be uppercase. Example: `"GET"`, `"POST"`, `"PUT"`, etc

#### headers

A dictionary-like (`scrapy.http.headers.Headers`) object which contains
the request headers.

#### body

The request body as bytes.

This attribute is read-only. To change the body of a Request use
[`replace()`](#scrapy.Request.replace).

#### callback *: CallbackT | [None](https://docs.python.org/3/library/constants.html#None)*

[`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable) to parse the
[`Response`](#scrapy.http.Response) to this request once received.

The callable must expect the response as its first parameter, and
support any additional keyword arguments set through
[`cb_kwargs`](#scrapy.Request.cb_kwargs). See [Writing a callback](#writing-callbacks) and
[Callback output](#callback-output).

In addition to an arbitrary callable, the following values are also
supported:

- `None` (default), which indicates that the
  [`parse()`](spiders.md#scrapy.Spider.parse) method of the spider must be used.
- [`NO_CALLBACK()`](#scrapy.http.request.NO_CALLBACK).

If an unhandled exception is raised during request or response
processing, i.e. by a [spider middleware](spider-middleware.md#topics-spider-middleware), [downloader middleware](downloader-middleware.md#topics-downloader-middleware) or download handler
([`DOWNLOAD_HANDLERS`](settings.md#std-setting-DOWNLOAD_HANDLERS)), [`errback`](#scrapy.Request.errback) is called instead.

> [!TIP]
> [`HttpErrorMiddleware`](spider-middleware.md#scrapy.spidermiddlewares.httperror.HttpErrorMiddleware)
> raises exceptions for non-2xx responses by default, sending them
> to the [`errback`](#scrapy.Request.errback) instead.

> [!NOTE]
> ### See also
> 
> [Callbacks](#callbacks)

#### errback *: Callable[[Failure], Any] | [None](https://docs.python.org/3/library/constants.html#None)*

[`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable) to handle exceptions raised
during request or response processing.

The callable must expect a [`Failure`](https://docs.twisted.org/en/stable/api/twisted.python.failure.Failure.html) as
its first parameter.

> [!NOTE]
> ### See also
> 
> [Errbacks](#errbacks)

#### priority *: [int](https://docs.python.org/3/library/functions.html#int)*

Default: `0`

Value that the [scheduler](scheduler.md#topics-scheduler) may use for
request prioritization.

Built-in schedulers prioritize requests with a higher priority
value.

Negative values are allowed.

#### cb_kwargs

A dictionary that contains arbitrary metadata for this request. Its contents
will be passed to the Request’s callback as keyword arguments. It is empty
for new Requests, which means by default callbacks only get a
[`Response`](#scrapy.http.Response) object as argument.

This dict is [shallow copied](https://docs.python.org/3/library/copy.html) when the request is
cloned using the `copy()` or `replace()` methods, and can also be
accessed, in your spider, from the `response.cb_kwargs` attribute.

In case of a failure to process the request, this dict can be accessed as
`failure.request.cb_kwargs` in the request’s errback. For more information,
see [Accessing additional data in errback functions](#errback-cb-kwargs).

> [!NOTE]
> When [`JOBDIR`](settings.md#std-setting-JOBDIR) is set, requests are serialized to disk
> with [`pickle`](https://docs.python.org/3/library/pickle.html#module-pickle) (see [Request serialization](jobs.md#request-serialization)). As a result,
> the callback receives a deep copy of any object stored in
> `cb_kwargs`, so mutating such an object in the callback does not
> affect the original. Avoid relying on shared mutable state passed
> through `cb_kwargs` in that case.

#### meta *= {}*

> A dictionary of arbitrary metadata for the request.

> You may extend request metadata as you see fit.

> Request metadata can also be accessed through the
> [`meta`](#scrapy.http.Response.meta) attribute of a response.

> To pass your own data from one spider callback to another, use
> [`cb_kwargs`](#scrapy.Request.cb_kwargs) instead, see [Passing additional data to callback functions](#callback-data). However, request
> metadata may be the right choice in certain scenarios, such as to
> maintain some debugging data across all follow-up requests (e.g. the
> source URL).

> A common use of request metadata is to define request-specific
> parameters for Scrapy components (extensions, middlewares, etc.). For
> example, if you set [`dont_retry`](downloader-middleware.md#std-reqmeta-dont_retry) to `True`,
> [`RetryMiddleware`](downloader-middleware.md#scrapy.downloadermiddlewares.retry.RetryMiddleware) will never
> retry that request, even if it fails. See [Request.meta special keys](#topics-request-meta).

> You may also use request metadata in your custom Scrapy components, for
> example, to keep request state information relevant to your component.
> For example,
> [`RetryMiddleware`](downloader-middleware.md#scrapy.downloadermiddlewares.retry.RetryMiddleware) uses the
> [`retry_times`](downloader-middleware.md#std-reqmeta-retry_times) metadata key to keep track of how many times a
> request has been retried so far.

> Copying all the metadata of a previous request into a new, follow-up
> request in a spider callback is a bad practice, because request
> metadata may include metadata set by Scrapy components that is not
> meant to be copied into other requests. For example, copying the
> [`retry_times`](downloader-middleware.md#std-reqmeta-retry_times) metadata key into follow-up requests can lower
> the amount of retries allowed for those follow-up requests.

> You should only copy all request metadata from one request to another
> if the new request is meant to replace the old request, as is often the
> case when returning a request from a [downloader middleware](downloader-middleware.md#topics-downloader-middleware) method.

> Also mind that the [`copy()`](#scrapy.Request.copy) and [`replace()`](#scrapy.Request.replace) request methods
> [shallow-copy](https://docs.python.org/3/library/copy.html) request metadata.

> > [!NOTE]
> > ### See also
> > 
> > [`MetaCopyDetectionMiddleware`](spider-middleware.md#scrapy.spidermiddlewares.metacopy.MetaCopyDetectionMiddleware)
> > for a built-in middleware that warns about this issue at run time.

#### dont_filter *: [bool](https://docs.python.org/3/library/functions.html#bool)*

Whether this request may be filtered out by [components](components.md#topics-components) that support filtering out requests (`False`,
default), or those components should not filter out this request
(`True`).

The following built-in components check this attribute:

- The [scheduler](scheduler.md#topics-scheduler) uses it to skip
  duplicate request filtering (see
  [`DUPEFILTER_CLASS`](settings.md#std-setting-DUPEFILTER_CLASS)). When set to `True`, the
  request is not checked against the duplicate filter,
  allowing requests that would otherwise be considered duplicates
  to be scheduled multiple times.
- [`OffsiteMiddleware`](downloader-middleware.md#scrapy.downloadermiddlewares.offsite.OffsiteMiddleware)
  uses it to allow requests to domains not in
  [`allowed_domains`](spiders.md#scrapy.Spider.allowed_domains). To skip only the offsite
  filter without affecting other components, consider using the
  [`allow_offsite`](downloader-middleware.md#std-reqmeta-allow_offsite) request meta key instead.

Third-party components may also use this attribute to decide whether
to filter out a request.

When defining the start URLs of a spider through
[`start_urls`](spiders.md#scrapy.Spider.start_urls), this attribute is enabled by
default. See [`start()`](spiders.md#scrapy.Spider.start).

#### attributes *: [tuple](https://docs.python.org/3/library/stdtypes.html#tuple)[[str](https://docs.python.org/3/library/stdtypes.html#str), ...]* *= ('url', 'headers', 'body', 'cookies', 'meta', 'encoding', 'flags', 'cb_kwargs', 'callback', 'dont_filter', 'errback', 'method', 'priority')*

A tuple of [`str`](https://docs.python.org/3/library/stdtypes.html#str) objects containing the name of all public
attributes of the class that are also keyword parameters of the
`__init__()` method.

Currently used by [`Request.replace()`](#scrapy.Request.replace), [`Request.to_dict()`](#scrapy.Request.to_dict) and
[`request_from_dict()`](#scrapy.utils.request.request_from_dict).

#### copy()

Return a new Request which is a copy of this Request. See also:
[Passing additional data to callback functions](#callback-data).

#### replace([urlmethodheadersbodycookiesmetaflagsencodingprioritydont_filtercallbackerrbackcb_kwargscls], , , , , , , , , , , , ,)

Return a Request object with the same members, except for those members
given new values by whichever keyword arguments are specified. The
[`cb_kwargs`](#scrapy.Request.cb_kwargs) and [`meta`](#scrapy.Request.meta) attributes are shallow
copied by default (unless new values are given as arguments). See also
[Passing additional data to callback functions](#callback-data).

#### *classmethod* from_curl(curl_command: [str](https://docs.python.org/3/library/stdtypes.html#str), ignore_unknown_options: [bool](https://docs.python.org/3/library/functions.html#bool) = True, \*\*kwargs: Any) → Self

Create a Request object from a string containing a [cURL](https://curl.se/) command. It populates the HTTP method, the
URL, the headers, the cookies and the body. It accepts the same
arguments as the [`Request`](#scrapy.Request) class, taking preference and
overriding the values of the same arguments contained in the cURL
command.

Unrecognized options are ignored by default. To raise an error when
finding unknown options call this method by passing
`ignore_unknown_options=False`.

> [!CAUTION]
> Using [`from_curl()`](#scrapy.Request.from_curl) from [`Request`](#scrapy.Request)
> subclasses, such as [`JsonRequest`](#scrapy.http.JsonRequest), or
> `XmlRpcRequest`, as well as having
> [downloader middlewares](downloader-middleware.md#topics-downloader-middleware)
> and
> [spider middlewares](spider-middleware.md#topics-spider-middleware)
> enabled, such as
> [`DefaultHeadersMiddleware`](downloader-middleware.md#scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware),
> [`UserAgentMiddleware`](downloader-middleware.md#scrapy.downloadermiddlewares.useragent.UserAgentMiddleware),
> or
> [`HttpCompressionMiddleware`](downloader-middleware.md#scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware),
> may modify the [`Request`](#scrapy.Request) object.

To translate a cURL command into a Scrapy request,
you may use [curl2scrapy](https://michael-shub.github.io/curl2scrapy/).

#### to_curl() → [str](https://docs.python.org/3/library/stdtypes.html#str)

Return a string with a [cURL](https://curl.se/) command equivalent
to this request.

Inverse of [`from_curl()`](#scrapy.Request.from_curl). See also
`scrapy.utils.request.request_to_curl()`.

> [!WARNING]
> Added in version 2.18.0.

#### to_dict(\*, spider: [Spider](spiders.md#scrapy.spiders.Spider) | [None](https://docs.python.org/3/library/constants.html#None) = None) → [dict](https://docs.python.org/3/library/stdtypes.html#dict)[[str](https://docs.python.org/3/library/stdtypes.html#str), [Any](https://docs.python.org/3/library/typing.html#typing.Any)]

Return a dictionary containing the Request’s data.

Use [`request_from_dict()`](#scrapy.utils.request.request_from_dict) to convert back into a [`Request`](#scrapy.Request) object.

If a spider is given, this method will try to find out the name of the spider methods used as callback
and errback and include them in the output dict, raising an exception if they cannot be found.

<a id="form"></a>

### Creating requests that submit HTML forms

Use [form2request](https://form2request.readthedocs.io/en/latest/index.html) to build request data from an HTML
`<form>` element and convert it to a [`Request`](#scrapy.Request).

Install it with pip:

```bash
pip install form2request
```

Select the desired form with CSS or XPath, then build and convert request
data:

```python
from form2request import form2request


def parse(self, response):
    form = response.css("form#search")
    request_data = form2request(form, data={"q": "scrapy"})
    yield request_data.to_scrapy(callback=self.parse_results)
```

Use `data` to override field values. To drop a field from the resulting
request, set its value to `None`.

By default, form2request simulates clicking the first submit button. To submit
without clicking any button, pass `click=False`. To click a specific submit
button, pass its element:

```python
def parse(self, response):
    form = response.css("form#checkout")
    submit = form.css('button[name="pay"]')
    request_data = form2request(form, click=submit)
```

<a id="topics-request-response-ref-request-userlogin"></a>

#### Using form2request to simulate a user login

It is usual for web sites to provide pre-populated form fields through `<input
type="hidden">` elements, such as session related data or authentication
tokens (for login pages). Build the request from the form and only override the
credentials:

```python
import scrapy
from form2request import form2request


class LoginSpider(scrapy.Spider):
    name = "example.com"
    start_urls = ["http://www.example.com/users/login.php"]

    def parse(self, response):
        form = response.css("form")
        request_data = form2request(
            form,
            data={"username": "john", "password": "secret"},
        )
        yield request_data.to_scrapy(callback=self.after_login)

    def after_login(self, response): ...
```

### Other functions related to requests

### scrapy.http.request.NO_CALLBACK(\*args: [Any](https://docs.python.org/3/library/typing.html#typing.Any), \*\*kwargs: [Any](https://docs.python.org/3/library/typing.html#typing.Any)) → [NoReturn](https://docs.python.org/3/library/typing.html#typing.NoReturn)

When assigned to the `callback` parameter of
[`Request`](#scrapy.Request), it indicates that the request is not meant
to have a spider callback at all.

For example:

```python
Request("https://example.com", callback=NO_CALLBACK)
```

This value should be used by [components](components.md#topics-components) that
create and handle their own requests, e.g. through
`scrapy.core.engine.ExecutionEngine.download()`, so that downloader
middlewares handling such requests can treat them differently from requests
intended for the [`parse()`](spiders.md#scrapy.Spider.parse) callback.

### scrapy.utils.request.request_from_dict(d: [dict](https://docs.python.org/3/library/stdtypes.html#dict)[[str](https://docs.python.org/3/library/stdtypes.html#str), [Any](https://docs.python.org/3/library/typing.html#typing.Any)], \*, spider: [Spider](spiders.md#scrapy.spiders.Spider) | [None](https://docs.python.org/3/library/constants.html#None) = None) → [Request](#scrapy.Request)

Create a [`Request`](#scrapy.Request) object from a dict.

If a spider is given, it will try to resolve the callbacks looking at the
spider for methods with the same name.

### scrapy.utils.httpobj.urlparse_cached(request_or_response: [Request](#scrapy.Request) | [Response](#scrapy.http.Response)) → ParseResult

Return the result of parsing the URL of *request_or_response*, a
[`Request`](#scrapy.Request) or [`Response`](#scrapy.http.Response) object, with
[`urllib.parse.urlparse()`](https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlparse).

The result is cached, using a [`weakref.WeakKeyDictionary`](https://docs.python.org/3/library/weakref.html#weakref.WeakKeyDictionary) keyed on
*request_or_response*, so that the URL of a given object is parsed only
once. Prefer this function over calling [`urllib.parse.urlparse()`](https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlparse) on
`request_or_response.url` directly when the same URL may be parsed more
than once.

<a id="request-fingerprints"></a>

### Request fingerprints

There are some aspects of scraping, such as filtering out duplicate requests
(see [`DUPEFILTER_CLASS`](settings.md#std-setting-DUPEFILTER_CLASS)) or caching responses (see
[`HTTPCACHE_POLICY`](downloader-middleware.md#std-setting-HTTPCACHE_POLICY)), where you need the ability to generate a short,
unique identifier from a [`Request`](#scrapy.Request) object: a request
fingerprint.

You often do not need to worry about request fingerprints, the default request
fingerprinter works for most projects.

However, there is no universal way to generate a unique identifier from a
request, because different situations require comparing requests differently.
For example, sometimes you may need to compare URLs case-insensitively, include
URL fragments, exclude certain URL query parameters, include some or all
headers, etc.

To change how request fingerprints are built for your requests, use the
[`REQUEST_FINGERPRINTER_CLASS`](#std-setting-REQUEST_FINGERPRINTER_CLASS) setting.

<a id="std-setting-REQUEST_FINGERPRINTER_CLASS"></a>

#### REQUEST_FINGERPRINTER_CLASS

Default: [`scrapy.utils.request.RequestFingerprinter`](#scrapy.utils.request.RequestFingerprinter)

A [request fingerprinter class](#custom-request-fingerprinter) or its
import path.

### *class* scrapy.utils.request.RequestFingerprinter(crawler: [Crawler](api.md#scrapy.crawler.Crawler) | [None](https://docs.python.org/3/library/constants.html#None) = None)

Default fingerprinter.

It takes into account a canonical version
([`w3lib.url.canonicalize_url()`](https://w3lib.readthedocs.io/en/latest/w3lib.html#w3lib.url.canonicalize_url)) of [`request.url`](#scrapy.Request.url) and the values of [`request.method`](#scrapy.Request.method) and [`request.body`](#scrapy.Request.body), unless [`verbatim_url`](#std-reqmeta-verbatim_url) is true for that
request. It then generates an [SHA1](https://en.wikipedia.org/wiki/SHA-1)
hash.

<a id="custom-request-fingerprinter"></a>

#### Writing your own request fingerprinter

A request fingerprinter is a [component](components.md#topics-components) that must
implement the following method:

### fingerprint(self, request: [scrapy.Request](#scrapy.Request))

Return a [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes) object that uniquely identifies *request*.

See also [Request fingerprint restrictions](#request-fingerprint-restrictions).

The [`fingerprint()`](#fingerprint) method of the default request fingerprinter,
[`scrapy.utils.request.RequestFingerprinter`](#scrapy.utils.request.RequestFingerprinter), uses
[`scrapy.utils.request.fingerprint()`](#scrapy.utils.request.fingerprint) with its default parameters. For some
common use cases you can use [`scrapy.utils.request.fingerprint()`](#scrapy.utils.request.fingerprint) as well
in your [`fingerprint()`](#fingerprint) method implementation:

### scrapy.utils.request.fingerprint(request: [Request](#scrapy.Request), \*, include_headers: Iterable[[bytes](https://docs.python.org/3/library/stdtypes.html#bytes) | [str](https://docs.python.org/3/library/stdtypes.html#str)] | [None](https://docs.python.org/3/library/constants.html#None) = None, keep_fragments: [bool](https://docs.python.org/3/library/functions.html#bool) = False) → [bytes](https://docs.python.org/3/library/stdtypes.html#bytes)

Return the request fingerprint.

The request fingerprint is a hash that uniquely identifies the resource the
request points to. For example, take the following two urls:
`http://www.example.com/query?id=111&cat=222`,
`http://www.example.com/query?cat=222&id=111`.

Even though those are two different URLs both point to the same resource
and are equivalent (i.e. they should return the same response).

Another example are cookies used to store session ids. Suppose the
following page is only accessible to authenticated users:
`http://www.example.com/members/offers.html`.

Lots of sites use a cookie to store the session id, which adds a random
component to the HTTP Request and thus should be ignored when calculating
the fingerprint.

For this reason, request headers are ignored by default when calculating
the fingerprint. If you want to include specific headers use the
include_headers argument, which is a list of Request headers to include.

Also, servers usually ignore fragments in urls when handling requests,
so they are also ignored by default when calculating the fingerprint.
If you want to include them, set the keep_fragments argument to True
(for instance when handling requests with a headless browser).

keep_fragments is not a substitute for rendering JavaScript to reach
content loaded based on the URL fragment; see
[Selecting dynamically-loaded content](dynamic-content.md#topics-dynamic-content) for that instead.

By default, request fingerprinting canonicalizes the request URL. If
[`verbatim_url`](#std-reqmeta-verbatim_url) is set to `True`, fingerprinting does not
canonicalize the URL, and the `keep_fragments` parameter is ignored (it is
effectively true).

For example, to take the value of a request header named `X-ID` into
account:

```python
# my_project/settings.py
REQUEST_FINGERPRINTER_CLASS = "my_project.utils.RequestFingerprinter"

# my_project/utils.py
from scrapy.utils.request import fingerprint


class RequestFingerprinter:
    def fingerprint(self, request):
        return fingerprint(request, include_headers=["X-ID"])
```

You can also write your own fingerprinting logic from scratch.

However, if you do not use [`scrapy.utils.request.fingerprint()`](#scrapy.utils.request.fingerprint), make sure
you use [`WeakKeyDictionary`](https://docs.python.org/3/library/weakref.html#weakref.WeakKeyDictionary) to cache request fingerprints:

- Caching saves CPU by ensuring that fingerprints are calculated only once
  per request, and not once per Scrapy component that needs the fingerprint
  of a request.
- Using [`WeakKeyDictionary`](https://docs.python.org/3/library/weakref.html#weakref.WeakKeyDictionary) saves memory by ensuring that
  request objects do not stay in memory forever just because you have
  references to them in your cache dictionary.

For example, to take into account only the URL of a request, without any prior
URL canonicalization or taking the request method or body into account:

```python
from hashlib import sha1
from weakref import WeakKeyDictionary

from scrapy.utils.python import to_bytes


class RequestFingerprinter:
    cache = WeakKeyDictionary()

    def fingerprint(self, request):
        if request not in self.cache:
            fp = sha1()
            fp.update(to_bytes(request.url))
            self.cache[request] = fp.digest()
        return self.cache[request]
```

If you need to be able to override the request fingerprinting for arbitrary
requests from your spider callbacks, you may implement a request fingerprinter
that reads fingerprints from [`request.meta`](#scrapy.Request.meta)
when available, and then falls back to
[`scrapy.utils.request.fingerprint()`](#scrapy.utils.request.fingerprint). For example:

```python
from scrapy.utils.request import fingerprint


class RequestFingerprinter:
    def fingerprint(self, request):
        if "fingerprint" in request.meta:
            return request.meta["fingerprint"]
        return fingerprint(request)
```

If you need to reproduce the same fingerprinting algorithm as Scrapy 2.6, use
the following request fingerprinter:

```python
from hashlib import sha1
from weakref import WeakKeyDictionary

from scrapy.utils.python import to_bytes
from w3lib.url import canonicalize_url


class RequestFingerprinter:
    cache = WeakKeyDictionary()

    def fingerprint(self, request):
        if request not in self.cache:
            fp = sha1()
            fp.update(to_bytes(request.method))
            fp.update(to_bytes(canonicalize_url(request.url)))
            fp.update(request.body or b"")
            self.cache[request] = fp.digest()
        return self.cache[request]
```

<a id="request-fingerprint-restrictions"></a>

#### Request fingerprint restrictions

Scrapy components that use request fingerprints may impose additional
restrictions on the format of the fingerprints that your [request
fingerprinter](#custom-request-fingerprinter) generates.

The following built-in Scrapy components have such restrictions:

- [`scrapy.extensions.httpcache.FilesystemCacheStorage`](downloader-middleware.md#scrapy.extensions.httpcache.FilesystemCacheStorage) (default
  value of [`HTTPCACHE_STORAGE`](downloader-middleware.md#std-setting-HTTPCACHE_STORAGE))

  Request fingerprints must be at least 1 byte long.

  Path and filename length limits of the file system of
  [`HTTPCACHE_DIR`](downloader-middleware.md#std-setting-HTTPCACHE_DIR) also apply. Inside [`HTTPCACHE_DIR`](downloader-middleware.md#std-setting-HTTPCACHE_DIR),
  the following directory structure is created:
  - [`Spider.name`](spiders.md#scrapy.Spider.name)
    - first byte of a request fingerprint as hexadecimal
      - fingerprint as hexadecimal
        - filenames up to 16 characters long

  For example, if a request fingerprint is made of 20 bytes (default),
  [`HTTPCACHE_DIR`](downloader-middleware.md#std-setting-HTTPCACHE_DIR) is `'/home/user/project/.scrapy/httpcache'`,
  and the name of your spider is `'my_spider'` your file system must
  support a file path like:
  ```
  /home/user/project/.scrapy/httpcache/my_spider/01/0123456789abcdef0123456789abcdef01234567/response_headers
  ```
- [`scrapy.extensions.httpcache.DbmCacheStorage`](downloader-middleware.md#scrapy.extensions.httpcache.DbmCacheStorage)

  The underlying DBM implementation must support keys as long as twice
  the number of bytes of a request fingerprint, plus 5. For example,
  if a request fingerprint is made of 20 bytes (default),
  45-character-long keys must be supported.

<a id="callbacks"></a>

## Callbacks

A callback is a function that Scrapy calls with the [`Response`](#scrapy.http.Response) of a
[`Request`](#scrapy.Request) once that request has been downloaded, so that you can
extract data from that response and generate additional requests to continue
the crawl:

```python
from scrapy import Request, Spider


class BookSpider(Spider):
    name = "books"

    async def start(self):
        yield Request("https://books.toscrape.com/", callback=self.parse_home)

    def parse_home(self, response):
        for url in response.css("h3 a::attr(href)").getall():
            yield Request(response.urljoin(url), callback=self.parse_book)

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

Requests may also define an [errback](#errbacks), which Scrapy calls
instead of the callback when an exception is raised while processing the
request or its response, e.g. a connection error or, by default, a non-2xx
response.

<a id="callback-assignment"></a>

### Assigning a callback to a request

To assign a callback to a request, use the `callback` parameter of
[`Request`](#scrapy.Request), which sets the [`Request.callback`](#scrapy.Request.callback) attribute:

```python
from scrapy import Request


def parse_home(response): ...


request = Request("https://books.toscrape.com/", callback=parse_home)
```

Requests with no callback, i.e. with [`callback`](#scrapy.Request.callback) set to
`None`, are handled by the [`parse()`](spiders.md#scrapy.Spider.parse) method of the spider:

```python
request = Request("https://books.toscrape.com/")  # Handled by parse()
```

If a request is never meant to reach a spider callback, e.g. because a
[component](components.md#topics-components) sends it and handles its response itself,
assign the special [`NO_CALLBACK()`](#scrapy.http.request.NO_CALLBACK) value to it
instead, so that [downloader middlewares](downloader-middleware.md#topics-downloader-middleware)
can tell such requests apart.

While [`callback`](#scrapy.Request.callback) only accepts callables, some spider
classes let you also define a callback by name: both [`CrawlSpider.rules`](spiders.md#scrapy.spiders.CrawlSpider.rules) and [`SitemapSpider.sitemap_rules`](spiders.md#scrapy.spiders.SitemapSpider.sitemap_rules) accept the name of a spider
method as a string.

<a id="writing-callbacks"></a>

### Writing a callback

Any callable can be a callback, as long as it takes the response as its first
positional parameter, and any [additional callback data](#callback-data)
as keyword parameters. Spider methods are the most common choice, but plain
functions, lambda expressions and other callable objects work as well.

> [!NOTE]
> If you enable [job persistence](jobs.md#topics-jobs) through the
> [`JOBDIR`](settings.md#std-setting-JOBDIR) setting, callbacks must be methods of the running spider.
> Requests with any other callback cannot be serialized, so they are kept in
> memory only and lost when you pause the crawl. See
> [Request serialization](jobs.md#request-serialization).

A callback can be:

- A regular function:
  ```python
  def parse(self, response):
      return {"url": response.url}
  ```
- A generator function:
  ```python
  def parse(self, response):
      yield {"url": response.url}
  ```
- A coroutine function, i.e. defined with `async def`:
  ```python
  async def parse(self, response):
      return {"url": response.url}
  ```
- An asynchronous generator function:
  ```python
  async def parse(self, response):
      yield {"url": response.url}
  ```

The last two allow using `await`, `async for` and `async with` in your
callback. See [Coroutines](coroutines.md#topics-coroutines).

<a id="callback-output"></a>

### Callback output

A callback may return or yield any of the following:

- `None`, which does nothing.

  Callbacks that produce no output at all, e.g. callbacks that only log
  information about the response, are perfectly valid. `None` values within
  an iterable of callback output are ignored as well.
- A [`Request`](#scrapy.Request) object, which Scrapy schedules, downloads and
  eventually sends to its own callback.
- An [item object](items.md#topics-items), which Scrapy sends to the
  [item pipelines](item-pipeline.md#topics-item-pipeline).

  Any object that is neither `None` nor a [`Request`](#scrapy.Request) object
  is treated as an item.
- An iterable of any of the values above, e.g. a list or, more commonly, a
  generator.

  [Asynchronous iterables](https://docs.python.org/3/glossary.html#term-asynchronous-iterable), e.g. an
  [asynchronous generator](https://docs.python.org/3/glossary.html#term-asynchronous-generator), are also supported.

> [!NOTE]
> When a callback *returns* an object, Scrapy iterates that object if
> it supports iteration, except for [`dict`](https://docs.python.org/3/library/stdtypes.html#dict), [`Item`](items.md#scrapy.Item),
> [`str`](https://docs.python.org/3/library/stdtypes.html#str) and [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes) objects, which are always handled as single
> items.

> [!NOTE]
> In a generator callback, a `return` statement with a value does not
> produce any output, since such a value is not part of what the generator
> yields. Scrapy logs a warning when it detects such a callback, see
> [`WARN_ON_GENERATOR_RETURN_VALUE`](settings.md#std-setting-WARN_ON_GENERATOR_RETURN_VALUE).

Before Scrapy acts on the output of a callback, that output goes through the
[`process_spider_output()`](spider-middleware.md#scrapy.spidermiddlewares.SpiderMiddleware.process_spider_output) method
of your [spider middlewares](spider-middleware.md#topics-spider-middleware), which may modify
it or drop part of it.

If a callback raises an exception, the [`errback`](#scrapy.Request.errback) of the
request is *not* called. The exception goes through the
[`process_spider_exception()`](spider-middleware.md#scrapy.spidermiddlewares.SpiderMiddleware.process_spider_exception)
method of your spider middlewares instead and, unless one of them handles it,
Scrapy logs it and sends the [`spider_error`](signals.md#std-signal-spider_error) signal.

<a id="callback-data"></a>

<a id="topics-request-response-ref-request-callback-arguments"></a>

### Passing additional data to callback functions

In some cases you may be interested in passing data to a callback in addition
to the response, e.g. data extracted from the response that triggered the
request. The following example shows how to achieve this by using the
[`Request.cb_kwargs`](#scrapy.Request.cb_kwargs) attribute:

```python
from scrapy import Request


def parse(self, response):
    request = Request(
        "http://www.example.com/index.html",
        callback=self.parse_page2,
        cb_kwargs=dict(main_url=response.url),
    )
    request.cb_kwargs["foo"] = "bar"  # add more arguments for the callback
    yield request


def parse_page2(self, response, main_url, foo):
    yield dict(
        main_url=main_url,
        other_url=response.url,
        foo=foo,
    )
```

[`Request.cb_kwargs`](#scrapy.Request.cb_kwargs) is the recommended way to pass your own data to a
callback. Use [`Request.meta`](#scrapy.Request.meta) only for data aimed at [components](components.md#topics-components), such as middlewares and extensions.

<a id="errbacks"></a>

<a id="topics-request-response-ref-errbacks"></a>

## Errbacks

The errback of a request is a function that will be called when an exception
is raised while processing it.

It receives a [`Failure`](https://docs.twisted.org/en/stable/api/twisted.python.failure.Failure.html) as first parameter and can
be used to track connection establishment timeouts, DNS errors etc.

Scrapy sets the `request` attribute of that
[`Failure`](https://docs.twisted.org/en/stable/api/twisted.python.failure.Failure.html) object to the [`Request`](#scrapy.Request)
object being processed.

If an errback raises an exception, Scrapy logs it and sends the
[`spider_error`](signals.md#std-signal-spider_error) signal, unless the exception is the one that the errback
received, which Scrapy logs as a download error instead.

Here’s an example spider logging all errors and catching some specific
errors if needed:

```python
from scrapy import Request, Spider
from scrapy.spidermiddlewares.httperror import HttpError
from twisted.internet.error import DNSLookupError
from twisted.internet.error import TimeoutError, TCPTimedOutError


class ErrbackSpider(Spider):
    name = "errback_example"
    start_urls = [
        "http://www.httpbin.org/",  # HTTP 200 expected
        "http://www.httpbin.org/status/404",  # Not found error
        "http://www.httpbin.org/status/500",  # server issue
        "http://www.httpbin.org:12345/",  # non-responding host, timeout expected
        "https://example.invalid/",  # DNS error expected
    ]

    async def start(self):
        for u in self.start_urls:
            yield Request(
                u,
                callback=self.parse_httpbin,
                errback=self.errback_httpbin,
                dont_filter=True,
            )

    def parse_httpbin(self, response):
        self.logger.info(f"Got successful response from {response.url}")
        # do something useful here...

    def errback_httpbin(self, failure):
        # log all failures
        self.logger.error(repr(failure))

        # in case you want to do something special for some errors,
        # you may need the failure's type:

        if failure.check(HttpError):
            # these exceptions come from HttpError spider middleware
            # you can get the non-200 response
            response = failure.value.response
            self.logger.error("HttpError on %s", response.url)

        elif failure.check(DNSLookupError):
            # this is the original request
            request = failure.request
            self.logger.error("DNSLookupError on %s", request.url)

        elif failure.check(TimeoutError, TCPTimedOutError):
            request = failure.request
            self.logger.error("TimeoutError on %s", request.url)
```

<a id="errback-cb-kwargs"></a>

### Accessing additional data in errback functions

In case of a failure to process the request, you may be interested in
accessing arguments to the callback functions so you can process further
based on the arguments in the errback. The following example shows how to
achieve this by using `Failure.request.cb_kwargs`:

```python
from scrapy import Request


def parse(self, response):
    request = Request(
        "http://www.example.com/index.html",
        callback=self.parse_page2,
        errback=self.errback_page2,
        cb_kwargs=dict(main_url=response.url),
    )
    yield request


def parse_page2(self, response, main_url):
    pass


def errback_page2(self, failure):
    yield dict(
        main_url=failure.request.cb_kwargs["main_url"],
    )
```

<a id="topics-request-meta"></a>

## Request.meta special keys

The [`Request.meta`](#scrapy.Request.meta) attribute can contain any arbitrary data, but there
are some special keys recognized by Scrapy and its built-in extensions.

Those are:

* [`allow_offsite`](downloader-middleware.md#std-reqmeta-allow_offsite)
* [`autothrottle_dont_adjust_delay`](autothrottle.md#std-reqmeta-autothrottle_dont_adjust_delay)
* [`bindaddress`](#std-reqmeta-bindaddress)
* [`cache_timestamp`](downloader-middleware.md#std-reqmeta-cache_timestamp)
* [`cookiejar`](cookies.md#std-reqmeta-cookiejar)
* [`depth`](spider-middleware.md#std-reqmeta-depth)
* [`dont_cache`](downloader-middleware.md#std-reqmeta-dont_cache)
* [`dont_merge_cookies`](cookies.md#std-reqmeta-dont_merge_cookies)
* [`dont_obey_robotstxt`](downloader-middleware.md#std-reqmeta-dont_obey_robotstxt)
* [`dont_redirect`](downloader-middleware.md#std-reqmeta-dont_redirect)
* [`dont_retry`](downloader-middleware.md#std-reqmeta-dont_retry)
* [`download_fail_on_dataloss`](#std-reqmeta-download_fail_on_dataloss)
* [`download_latency`](#std-reqmeta-download_latency)
* [`download_maxsize`](settings.md#std-reqmeta-download_maxsize)
* [`download_slot`](settings.md#std-reqmeta-download_slot)
* [`download_timeout`](#std-reqmeta-download_timeout)
* [`download_warnsize`](settings.md#std-reqmeta-download_warnsize)
* [`ftp_local_filename`](#std-reqmeta-ftp_local_filename)
* [`ftp_passive`](settings.md#std-reqmeta-ftp_passive)
* [`ftp_password`](settings.md#std-reqmeta-ftp_password)
* [`ftp_user`](settings.md#std-reqmeta-ftp_user)
* [`give_up_log_level`](#std-reqmeta-give_up_log_level)
* [`handle_httpstatus_all`](spider-middleware.md#std-reqmeta-handle_httpstatus_all)
* [`handle_httpstatus_list`](spider-middleware.md#std-reqmeta-handle_httpstatus_list)
* [`http_auth_domain`](#std-reqmeta-http_auth_domain)
* [`http_pass`](#std-reqmeta-http_pass)
* [`http_user`](#std-reqmeta-http_user)
* [`is_start_request`](spider-middleware.md#std-reqmeta-is_start_request)
* [`link_text`](spiders.md#std-reqmeta-link_text)
* [`max_retry_times`](#std-reqmeta-max_retry_times)
* [`priority_adjust`](downloader-middleware.md#std-reqmeta-priority_adjust)
* [`proxy`](downloader-middleware.md#std-reqmeta-proxy)
* [`redirect_reasons`](downloader-middleware.md#std-reqmeta-redirect_reasons)
* [`redirect_times`](downloader-middleware.md#std-reqmeta-redirect_times)
* [`redirect_ttl`](downloader-middleware.md#std-reqmeta-redirect_ttl)
* [`redirect_urls`](downloader-middleware.md#std-reqmeta-redirect_urls)
* [`referrer_policy`](spider-middleware.md#std-reqmeta-referrer_policy)
* [`retry_times`](downloader-middleware.md#std-reqmeta-retry_times)
* [`rule`](spiders.md#std-reqmeta-rule)
* [`verbatim_url`](#std-reqmeta-verbatim_url)

Scrapy components also use meta keys whose name starts with an underscore, such
as `_auth_proxy`. Those are internal, and may change or disappear at any time.

<a id="std-reqmeta-bindaddress"></a>

### bindaddress

The default local outgoing address for download-handler connections.

This meta value can be either:

- a host address as a string (e.g. `"127.0.0.2"`), in which case the local
  port is chosen automatically, or
- a `(host, port)` tuple (e.g. `("127.0.0.2", 50000)`) to bind to both a
  specific local interface and a specific local port.

For example:

```python
Request(
    "https://example.org",
    meta={"bindaddress": "127.0.0.2"},
)
```

```python
Request(
    "https://example.org",
    meta={"bindaddress": ("127.0.0.2", 50000)},
)
```

If not set, built-in HTTP download handlers use the value of
[`DOWNLOAD_BIND_ADDRESS`](settings.md#std-setting-DOWNLOAD_BIND_ADDRESS) as the default bind address.
Set the [`bindaddress`](#std-reqmeta-bindaddress) request meta key to override it for a
specific request.

This meta key is not supported by
[`HttpxDownloadHandler`](download-handlers.md#scrapy.core.downloader.handlers._httpx.HttpxDownloadHandler) and
[`AiohttpDownloadHandler`](download-handlers.md#scrapy.core.downloader.handlers._aiohttp.AiohttpDownloadHandler), but
the [`DOWNLOAD_BIND_ADDRESS`](settings.md#std-setting-DOWNLOAD_BIND_ADDRESS) setting is supported by them.

<a id="std-reqmeta-download_timeout"></a>

### download_timeout

The amount of time (in secs) that the downloader will wait before timing out.
See also: [`DOWNLOAD_TIMEOUT`](settings.md#std-setting-DOWNLOAD_TIMEOUT).

<a id="std-reqmeta-download_latency"></a>

### download_latency

The amount of time spent to fetch the response, since the request has been
started, i.e. HTTP message sent over the network. This meta key only becomes
available when the response has been downloaded. While most other meta keys are
used to control Scrapy behavior, this one is supposed to be read-only.

<a id="std-reqmeta-download_fail_on_dataloss"></a>

### download_fail_on_dataloss

Whether or not to fail on broken responses. See:
[`DOWNLOAD_FAIL_ON_DATALOSS`](settings.md#std-setting-DOWNLOAD_FAIL_ON_DATALOSS).

<a id="std-reqmeta-ftp_local_filename"></a>

### ftp_local_filename

Path, as [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes), of the file where to write the response body of an
`ftp://` request. If set, [`Response.body`](#scrapy.http.Response.body)
holds this path instead of the file contents.

<a id="std-reqmeta-give_up_log_level"></a>

### give_up_log_level

> [!WARNING]
> Added in version 2.17.0.

[Logging level](https://docs.python.org/3/library/logging.html#levels) used for the message logged when a request
exceeds its retries. See [`RETRY_GIVE_UP_LOG_LEVEL`](downloader-middleware.md#std-setting-RETRY_GIVE_UP_LOG_LEVEL) for details.

<a id="std-reqmeta-http_auth_domain"></a>

### http_auth_domain

> [!WARNING]
> Added in version 2.17.0.

Overrides [`HTTPAUTH_DOMAIN`](downloader-middleware.md#std-setting-HTTPAUTH_DOMAIN) for this request.

<a id="std-reqmeta-http_pass"></a>

### http_pass

> [!WARNING]
> Added in version 2.17.0.

Overrides [`HTTPAUTH_PASS`](downloader-middleware.md#std-setting-HTTPAUTH_PASS) for this request.

<a id="std-reqmeta-http_user"></a>

### http_user

> [!WARNING]
> Added in version 2.17.0.

Overrides [`HTTPAUTH_USER`](downloader-middleware.md#std-setting-HTTPAUTH_USER) for this request.

<a id="std-reqmeta-max_retry_times"></a>

### max_retry_times

The meta key is used set retry times per request. When set, the
[`max_retry_times`](#std-reqmeta-max_retry_times) meta key takes higher precedence over the
[`RETRY_TIMES`](downloader-middleware.md#std-setting-RETRY_TIMES) setting.

<a id="std-reqmeta-verbatim_url"></a>

### verbatim_url

> [!WARNING]
> Added in version 2.17.0.

Set this key to `True` to keep the request URL as passed to
[`Request`](#scrapy.Request), without URL percent-encoding.

When this key is enabled, [`fingerprint()`](#scrapy.utils.request.fingerprint) does not
canonicalize the request URL, so requests whose URLs differ only in
characters that would otherwise be canonicalized get different fingerprints.

In this mode, the `keep_fragments` parameter is ignored, and it is
effectively true.

<a id="topics-stop-response-download"></a>

## Stopping the download of a Response

Raising a [`StopDownload`](exceptions.md#scrapy.exceptions.StopDownload) exception from a handler for the
[`bytes_received`](signals.md#scrapy.signals.bytes_received) or [`headers_received`](signals.md#scrapy.signals.headers_received)
signals will stop the download of a given response. See the following example:

```python
import scrapy


class StopSpider(scrapy.Spider):
    name = "stop"
    start_urls = ["https://docs.scrapy.org/en/latest/"]

    @classmethod
    def from_crawler(cls, crawler):
        spider = super().from_crawler(crawler)
        crawler.signals.connect(
            spider.on_bytes_received, signal=scrapy.signals.bytes_received
        )
        return spider

    def parse(self, response):
        # 'last_chars' show that the full response was not downloaded
        yield {"len": len(response.text), "last_chars": response.text[-40:]}

    def on_bytes_received(self, data, request, spider):
        raise scrapy.exceptions.StopDownload(fail=False)
```

which produces the following output:

```
2020-05-19 17:26:12 [scrapy.core.engine] INFO: Spider opened
2020-05-19 17:26:12 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2020-05-19 17:26:13 [scrapy.core.downloader.handlers.http11] DEBUG: Download stopped for <GET https://docs.scrapy.org/en/latest/> from signal handler StopSpider.on_bytes_received
2020-05-19 17:26:13 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://docs.scrapy.org/en/latest/> (referer: None) ['download_stopped']
2020-05-19 17:26:13 [scrapy.core.scraper] DEBUG: Scraped from <200 https://docs.scrapy.org/en/latest/>
{'len': 279, 'last_chars': 'dth, initial-scale=1.0">\n  \n  <title>Scr'}
2020-05-19 17:26:13 [scrapy.core.engine] INFO: Closing spider (finished)
```

By default, resulting responses are handled by their corresponding errbacks. To
call their callback instead, like in this example, pass `fail=False` to the
[`StopDownload`](exceptions.md#scrapy.exceptions.StopDownload) exception.

<a id="topics-request-response-ref-request-subclasses"></a>

## Request subclasses

Here is the list of built-in [`Request`](#scrapy.Request) subclasses. You can also subclass
it to implement your own custom functionality.

### FormRequest

### *class* scrapy.FormRequest(\*args: Any, \*\*kwargs: Any)

A [`Request`](#scrapy.Request) subclass with a `formdata` parameter that
url-encodes the given data and assigns it to the request, which makes it
convenient to send arbitrary form data via HTTP POST or GET without an HTML
`<form>` element to parse.

> [!NOTE]
> To build a request from an HTML `<form>` element found in a
> response, use [form2request](https://form2request.readthedocs.io/en/latest/index.html) instead. See
> [Creating requests that submit HTML forms](#form).

The remaining arguments are the same as for the [`Request`](#scrapy.Request)
class and are not documented here.

* **Parameters:**
  **formdata** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict) *or* [*collections.abc.Iterable*](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable)) – a dictionary (or iterable of (key, value) tuples)
  containing HTML form data which will be url-encoded. If
  [`method`](#scrapy.Request.method) is not given and `formdata` is
  provided, the method is set to `"POST"` and the data is assigned to
  the request body; if the method is `"GET"`, the data is added to the
  URL query string instead.

To send data via HTTP POST, simulating an HTML form submission, return a
[`FormRequest`](#scrapy.FormRequest) object from your spider:

<!-- skip: next -->
```python
return [
    FormRequest(
        url="http://www.example.com/post/action",
        formdata={"name": "John Doe", "age": "27"},
        callback=self.after_post,
    )
]
```

To send the data in the URL query string instead, use the `GET` method:

<!-- skip: next -->
```python
return [
    FormRequest(
        url="http://www.example.com/search",
        method="GET",
        formdata={"q": "keyword", "page": "1"},
        callback=self.parse_results,
    )
]
```

### JsonRequest

The JsonRequest class extends the base [`Request`](#scrapy.Request) class with functionality for
dealing with JSON requests.

### *class* scrapy.http.JsonRequest([... datadumps_kwargs]url, ,)

The [`JsonRequest`](#scrapy.http.JsonRequest) class adds two new keyword parameters to the `__init__()` method. The
remaining arguments are the same as for the [`Request`](#scrapy.Request) class and are
not documented here.

Using the [`JsonRequest`](#scrapy.http.JsonRequest) will set the `Content-Type` header to `application/json`
and `Accept` header to `application/json, text/javascript, */*; q=0.01`

* **Parameters:**
  * **data** ([*object*](https://docs.python.org/3/library/functions.html#object)) – is any JSON serializable object that needs to be JSON encoded and assigned to body.
    If the [`body`](#scrapy.Request.body) argument is provided this parameter will be ignored.
    If the [`body`](#scrapy.Request.body) argument is not provided and the
    `data` argument is provided the [`method`](#scrapy.Request.method) will be
    set to `'POST'` automatically.
  * **dumps_kwargs** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict)) – Parameters that will be passed to underlying [`json.dumps()`](https://docs.python.org/3/library/json.html#json.dumps) method which is used to serialize
    data into JSON format.

#### attributes *: [tuple](https://docs.python.org/3/library/stdtypes.html#tuple)[[str](https://docs.python.org/3/library/stdtypes.html#str), ...]* *= ('url', 'headers', 'body', 'cookies', 'meta', 'encoding', 'flags', 'cb_kwargs', 'callback', 'dont_filter', 'errback', 'method', 'priority', 'dumps_kwargs')*

A tuple of [`str`](https://docs.python.org/3/library/stdtypes.html#str) objects containing the name of all public
attributes of the class that are also keyword parameters of the
`__init__()` method.

Currently used by [`Request.replace()`](#scrapy.Request.replace), [`Request.to_dict()`](#scrapy.Request.to_dict) and
[`request_from_dict()`](#scrapy.utils.request.request_from_dict).

### JsonRequest usage example

Sending a JSON POST request with a JSON payload:

<!-- skip: next -->
```python
data = {
    "name1": "value1",
    "name2": "value2",
}
yield JsonRequest(url="http://www.example.com/post/action", data=data)
```

## Response objects

### *class* scrapy.http.Response(\*args: Any, \*\*kwargs: Any)

An object that represents an HTTP response, which is usually
downloaded (by the Downloader) and fed to the Spiders for processing.

* **Parameters:**
  * **url** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) – the URL of this response
  * **status** ([*int*](https://docs.python.org/3/library/functions.html#int)) – the HTTP status of the response. Defaults to `200`.
  * **headers** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict)) – the headers of this response. The dict values can be strings
    (for single valued headers) or lists (for multi-valued headers).
  * **body** ([*bytes*](https://docs.python.org/3/library/stdtypes.html#bytes)) – the response body. To access the decoded text as a string, use
    `response.text` from an encoding-aware
    [Response subclass](#topics-request-response-ref-response-subclasses),
    such as [`TextResponse`](#scrapy.http.TextResponse).
  * **flags** ([*list*](https://docs.python.org/3/library/stdtypes.html#list)) – is a list containing the initial values for the
    [`Response.flags`](#scrapy.http.Response.flags) attribute. If given, the list will be shallow
    copied.
  * **request** ([*scrapy.Request*](#scrapy.Request)) – the initial value of the [`Response.request`](#scrapy.http.Response.request) attribute.
    This represents the [`Request`](#scrapy.Request) that generated this response.
  * **certificate** ([*Any*](https://docs.python.org/3/library/typing.html#typing.Any)) – an object representing the server’s SSL certificate.
  * **ip_address** ([`ipaddress.IPv4Address`](https://docs.python.org/3/library/ipaddress.html#ipaddress.IPv4Address) or [`ipaddress.IPv6Address`](https://docs.python.org/3/library/ipaddress.html#ipaddress.IPv6Address)) – The IP address of the server from which the Response originated.
  * **protocol** ([`str`](https://docs.python.org/3/library/stdtypes.html#str)) – The protocol that was used to download the response.
    For instance: “HTTP/1.0”, “HTTP/1.1”, “h2”

#### url

A string containing the URL of the response.

This attribute is read-only. To change the URL of a Response use
[`replace()`](#scrapy.http.Response.replace).

#### status

An integer representing the HTTP status of the response. Example: `200`,
`404`.

#### headers

A dictionary-like (`scrapy.http.headers.Headers`) object which contains
the response headers. Values can be accessed using
`get()` to return the last header value with
the specified name or `getlist()` to return
all header values with the specified name. For example, this call will give you
all cookies in the headers:

<!-- skip: next -->
```python
response.headers.getlist("Set-Cookie")
```

#### body

The response body as bytes.

If you want the body as a string, use [`TextResponse.text`](#scrapy.http.TextResponse.text) (only
available in [`TextResponse`](#scrapy.http.TextResponse) and subclasses).

This attribute is read-only. To change the body of a Response use
[`replace()`](#scrapy.http.Response.replace).

#### request

The [`Request`](#scrapy.Request) object that generated this response. This attribute is
assigned in the Scrapy engine, after the response and the request have passed
through all [Downloader Middlewares](downloader-middleware.md#topics-downloader-middleware).
In particular, this means that:

- HTTP redirections will create a new request from the request before
  redirection. It has the majority of the same metadata and original
  request attributes and gets assigned to the redirected response
  instead of the propagation of the original request.
- Response.request.url doesn’t always equal Response.url
- This attribute is only available in the spider code, and in the
  [Spider Middlewares](spider-middleware.md#topics-spider-middleware), but not in
  Downloader Middlewares (although you have the Request available there by
  other means) and handlers of the [`response_downloaded`](signals.md#std-signal-response_downloaded) signal.

#### meta

A shortcut to the [`meta`](#scrapy.Request.meta) attribute of the
[`Response.request`](#scrapy.http.Response.request) object (i.e. `self.request.meta`).

Unlike the [`Response.request`](#scrapy.http.Response.request) attribute, the [`Response.meta`](#scrapy.http.Response.meta)
attribute is propagated along redirects and retries, so you will get
the original [`Request.meta`](#scrapy.Request.meta) sent from your spider.

> [!NOTE]
> ### See also
> 
> [`Request.meta`](#scrapy.Request.meta) attribute

#### cb_kwargs

A shortcut to the [`cb_kwargs`](#scrapy.Request.cb_kwargs) attribute of the
[`Response.request`](#scrapy.http.Response.request) object (i.e. `self.request.cb_kwargs`).

Unlike the [`Response.request`](#scrapy.http.Response.request) attribute, the
[`Response.cb_kwargs`](#scrapy.http.Response.cb_kwargs) attribute is propagated along redirects and
retries, so you will get the original [`Request.cb_kwargs`](#scrapy.Request.cb_kwargs) sent from your spider.

> [!NOTE]
> ### See also
> 
> [`Request.cb_kwargs`](#scrapy.Request.cb_kwargs) attribute

#### flags

A list that contains flags for this response. Flags are labels used for
tagging Responses. For example: `'cached'`, `'redirected'`’, etc. And
they’re shown on the string representation of the Response (`__str__()`
method) which is used by the engine for logging.

#### certificate

An object representing the server’s SSL certificate. Its type and
contents depend on the download handler that produced the response.

Only populated for `https` responses, `None` otherwise.

#### ip_address

The IP address of the server from which the Response originated.

This attribute is currently only populated by the HTTP download
handlers, i.e. for `http(s)` responses. For other handlers,
[`ip_address`](#scrapy.http.Response.ip_address) is always `None`.

#### protocol

The protocol that was used to download the response.
For instance: “HTTP/1.0”, “HTTP/1.1”

This attribute is currently only populated by the HTTP download
handlers, i.e. for `http(s)` responses. For other handlers,
[`protocol`](#scrapy.http.Response.protocol) is always `None`.

#### attributes *: [tuple](https://docs.python.org/3/library/stdtypes.html#tuple)[[str](https://docs.python.org/3/library/stdtypes.html#str), ...]* *= ('url', 'headers', 'body', 'flags', 'status', 'request', 'certificate', 'ip_address', 'protocol')*

A tuple of [`str`](https://docs.python.org/3/library/stdtypes.html#str) objects containing the name of all public
attributes of the class that are also keyword parameters of the
`__init__()` method.

Currently used by [`Response.replace()`](#scrapy.http.Response.replace).

#### copy()

Returns a new Response which is a copy of this Response.

#### replace([urlstatusheadersbodyrequestflagscertificateip_addressprotocolcls], , , , , , , , ,)

Returns a Response object with the same members, except for those members
given new values by whichever keyword arguments are specified. The
attribute [`Response.meta`](#scrapy.http.Response.meta) is copied by default.

#### urljoin(url)

Constructs an absolute url by combining the Response’s [`url`](#scrapy.http.Response.url) with
a possible relative url.

This is a wrapper over [`urljoin()`](https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urljoin), it’s merely an alias for
making this call:

<!-- skip: next -->
```python
urllib.parse.urljoin(response.url, url)
```

#### follow(url: [str](https://docs.python.org/3/library/stdtypes.html#str) | [Link](link-extractors.md#scrapy.link.Link), callback: CallbackT | [None](https://docs.python.org/3/library/constants.html#None) = None, method: [str](https://docs.python.org/3/library/stdtypes.html#str) = 'GET', headers: Mapping[[str](https://docs.python.org/3/library/stdtypes.html#str), Any] | Mapping[[bytes](https://docs.python.org/3/library/stdtypes.html#bytes), Any] | Iterable[[tuple](https://docs.python.org/3/library/stdtypes.html#tuple)[[str](https://docs.python.org/3/library/stdtypes.html#str) | [bytes](https://docs.python.org/3/library/stdtypes.html#bytes), Any]] | [None](https://docs.python.org/3/library/constants.html#None) = None, body: [bytes](https://docs.python.org/3/library/stdtypes.html#bytes) | [str](https://docs.python.org/3/library/stdtypes.html#str) | [None](https://docs.python.org/3/library/constants.html#None) = None, cookies: CookiesT | [None](https://docs.python.org/3/library/constants.html#None) = None, meta: [dict](https://docs.python.org/3/library/stdtypes.html#dict)[[str](https://docs.python.org/3/library/stdtypes.html#str), Any] | [None](https://docs.python.org/3/library/constants.html#None) = None, encoding: [str](https://docs.python.org/3/library/stdtypes.html#str) | [None](https://docs.python.org/3/library/constants.html#None) = 'utf-8', priority: [int](https://docs.python.org/3/library/functions.html#int) = 0, dont_filter: [bool](https://docs.python.org/3/library/functions.html#bool) = False, errback: Callable[[Failure], Any] | [None](https://docs.python.org/3/library/constants.html#None) = None, cb_kwargs: [dict](https://docs.python.org/3/library/stdtypes.html#dict)[[str](https://docs.python.org/3/library/stdtypes.html#str), Any] | [None](https://docs.python.org/3/library/constants.html#None) = None, flags: [list](https://docs.python.org/3/library/stdtypes.html#list)[[str](https://docs.python.org/3/library/stdtypes.html#str)] | [None](https://docs.python.org/3/library/constants.html#None) = None) → [Request](#scrapy.Request)

Return a [`Request`](#scrapy.Request) instance to follow a link `url`.
It accepts the same arguments as `Request.__init__()` method,
but `url` can be a relative URL or a [`Link`](link-extractors.md#scrapy.link.Link) object,
not only an absolute URL.

[`TextResponse`](#scrapy.http.TextResponse) provides a [`follow()`](#scrapy.http.TextResponse.follow)
method which supports selectors in addition to absolute/relative URLs
and Link objects.

#### follow_all(urls: Iterable[[str](https://docs.python.org/3/library/stdtypes.html#str) | [Link](link-extractors.md#scrapy.link.Link)], callback: CallbackT | [None](https://docs.python.org/3/library/constants.html#None) = None, method: [str](https://docs.python.org/3/library/stdtypes.html#str) = 'GET', headers: Mapping[[str](https://docs.python.org/3/library/stdtypes.html#str), Any] | Mapping[[bytes](https://docs.python.org/3/library/stdtypes.html#bytes), Any] | Iterable[[tuple](https://docs.python.org/3/library/stdtypes.html#tuple)[[str](https://docs.python.org/3/library/stdtypes.html#str) | [bytes](https://docs.python.org/3/library/stdtypes.html#bytes), Any]] | [None](https://docs.python.org/3/library/constants.html#None) = None, body: [bytes](https://docs.python.org/3/library/stdtypes.html#bytes) | [str](https://docs.python.org/3/library/stdtypes.html#str) | [None](https://docs.python.org/3/library/constants.html#None) = None, cookies: CookiesT | [None](https://docs.python.org/3/library/constants.html#None) = None, meta: [dict](https://docs.python.org/3/library/stdtypes.html#dict)[[str](https://docs.python.org/3/library/stdtypes.html#str), Any] | [None](https://docs.python.org/3/library/constants.html#None) = None, encoding: [str](https://docs.python.org/3/library/stdtypes.html#str) | [None](https://docs.python.org/3/library/constants.html#None) = 'utf-8', priority: [int](https://docs.python.org/3/library/functions.html#int) = 0, dont_filter: [bool](https://docs.python.org/3/library/functions.html#bool) = False, errback: Callable[[Failure], Any] | [None](https://docs.python.org/3/library/constants.html#None) = None, cb_kwargs: [dict](https://docs.python.org/3/library/stdtypes.html#dict)[[str](https://docs.python.org/3/library/stdtypes.html#str), Any] | [None](https://docs.python.org/3/library/constants.html#None) = None, flags: [list](https://docs.python.org/3/library/stdtypes.html#list)[[str](https://docs.python.org/3/library/stdtypes.html#str)] | [None](https://docs.python.org/3/library/constants.html#None) = None) → Iterable[[Request](#scrapy.Request)]

Return an iterable of [`Request`](#scrapy.Request) instances to follow all links
in `urls`. It accepts the same arguments as `Request.__init__()` method,
but elements of `urls` can be relative URLs or [`Link`](link-extractors.md#scrapy.link.Link) objects,
not only absolute URLs.

[`TextResponse`](#scrapy.http.TextResponse) provides a [`follow_all()`](#scrapy.http.TextResponse.follow_all)
method which supports selectors in addition to absolute/relative URLs
and Link objects.

> [!CAUTION]
> Every returned request gets its own *meta* and
> *cb_kwargs* dictionaries, but the values within them are shared.
> Mutating one of those values, e.g. appending to a list, affects
> all the returned requests.

#### to_dict() → [dict](https://docs.python.org/3/library/stdtypes.html#dict)[[str](https://docs.python.org/3/library/stdtypes.html#str), [Any](https://docs.python.org/3/library/typing.html#typing.Any)]

Return a dictionary containing the Response’s data.

> [!WARNING]
> Added in version 2.19.0.

Use [`response_from_dict()`](#scrapy.utils.response.response_from_dict) to convert back
into a [`Response`](#scrapy.http.Response) object.

[`request`](#scrapy.http.Response.request) and [`certificate`](#scrapy.http.Response.certificate) are left out, as they are tied
to a single crawl. Everything else in [`attributes`](#scrapy.http.Response.attributes) is included,
so subclasses only need to override this method, and [`from_dict()`](#scrapy.http.Response.from_dict),
if some of their attributes cannot be stored as is.

#### *classmethod* from_dict(d: [dict](https://docs.python.org/3/library/stdtypes.html#dict)[[str](https://docs.python.org/3/library/stdtypes.html#str), Any]) → Self

Return a response built from the *d* dict, as returned by
[`to_dict()`](#scrapy.http.Response.to_dict).

> [!WARNING]
> Added in version 2.19.0.

<a id="topics-request-response-ref-response-subclasses"></a>

## Response subclasses

Here is the list of available built-in Response subclasses. You can also
subclass the Response class to implement your own functionality.

### TextResponse objects

### *class* scrapy.http.TextResponse([encoding[...]]url, ,)

[`TextResponse`](#scrapy.http.TextResponse) objects adds encoding capabilities to the base
[`Response`](#scrapy.http.Response) class, which is meant to be used only for binary data,
such as images, sounds or any media file.

[`TextResponse`](#scrapy.http.TextResponse) objects support a new `__init__()` method argument, in
addition to the base [`Response`](#scrapy.http.Response) objects. The remaining functionality
is the same as for the [`Response`](#scrapy.http.Response) class and is not documented here.

* **Parameters:**
  **encoding** ([*str*](https://docs.python.org/3/library/stdtypes.html#str)) – is a string which contains the encoding to use for this
  response. If you create a [`TextResponse`](#scrapy.http.TextResponse) object with a string as
  body, it will be converted to bytes encoded using this encoding. If
  *encoding* is `None` (default), the encoding will be looked up in the
  response headers and body instead.

[`TextResponse`](#scrapy.http.TextResponse) objects support the following attributes in addition
to the standard [`Response`](#scrapy.http.Response) ones:

#### text

Response body, as a string.

The same as `response.body.decode(response.encoding)`, but the
result is cached after the first call, so you can access
`response.text` multiple times without extra overhead.

> [!NOTE]
> `str(response.body)` is not a correct way to convert the response
> body into a string:
> 
> ```pycon
> >>> str(b"body")
> "b'body'"
> ```

#### encoding

A string with the encoding of this response. The encoding is resolved by
trying the following mechanisms, in order:

1. the encoding passed in the `__init__()` method `encoding` argument
2. the encoding of the [byte order mark](https://en.wikipedia.org/wiki/Byte_order_mark) at the start of the response
   body
3. the encoding declared in the Content-Type HTTP header. If this
   encoding is not valid (i.e. unknown), it is ignored and the next
   resolution mechanism is tried.
4. the encoding declared in the response body. The TextResponse class
   doesn’t provide any special functionality for this. However, the
   [`HtmlResponse`](#scrapy.http.HtmlResponse) and [`XmlResponse`](#scrapy.http.XmlResponse) classes do.
5. the encoding inferred by looking at the response body. This is the more
   fragile method but also the last one tried.

This order matches the [encoding sniffing algorithm](https://html.spec.whatwg.org/multipage/parsing.html#determining-the-character-encoding) of the HTML
standard, which web browsers follow.

To resolve the encoding differently, determine it yourself and pass it
through [`Response.replace()`](#scrapy.http.Response.replace) from a [downloader middleware](downloader-middleware.md#topics-downloader-middleware). Give that middleware an order between
those of
[`MetaRefreshMiddleware`](downloader-middleware.md#scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware)
(580) and
[`HttpCompressionMiddleware`](downloader-middleware.md#scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware)
(590), so that it gets a decompressed body and no other component reads
the response text before it.

For example, to give a declaration in the response body precedence over
the Content-Type header:

```python
from w3lib.encoding import html_body_declared_encoding, read_bom

from scrapy.http import TextResponse


class BodyEncodingMiddleware:
    def process_response(self, request, response, spider):
        if not isinstance(response, TextResponse):
            return response
        if read_bom(response.body)[0]:
            return response
        encoding = html_body_declared_encoding(response.body)
        return response.replace(encoding=encoding) if encoding else response
```

#### selector

A [`Selector`](selectors.md#scrapy.Selector) instance using the response as
target. The selector is lazily instantiated on first access.

#### attributes *: [tuple](https://docs.python.org/3/library/stdtypes.html#tuple)[[str](https://docs.python.org/3/library/stdtypes.html#str), ...]* *= ('url', 'headers', 'body', 'flags', 'status', 'request', 'certificate', 'ip_address', 'protocol', 'encoding')*

A tuple of [`str`](https://docs.python.org/3/library/stdtypes.html#str) objects containing the name of all public
attributes of the class that are also keyword parameters of the
`__init__()` method.

Currently used by [`Response.replace()`](#scrapy.http.Response.replace).

[`TextResponse`](#scrapy.http.TextResponse) objects support the following methods in addition to
the standard [`Response`](#scrapy.http.Response) ones:

#### jmespath(query)

<!-- skip: start -->

A shortcut to `TextResponse.selector.jmespath(query)`:

```python
response.jmespath("object.[*]")
```

#### xpath(query)

A shortcut to `TextResponse.selector.xpath(query)`:

```python
response.xpath("//p")
```

#### css(query)

A shortcut to `TextResponse.selector.css(query)`:

```python
response.css("p")
```

<!-- skip: end -->

#### follow(url: [str](https://docs.python.org/3/library/stdtypes.html#str) | [Link](link-extractors.md#scrapy.link.Link) | parsel.Selector, callback: CallbackT | [None](https://docs.python.org/3/library/constants.html#None) = None, method: [str](https://docs.python.org/3/library/stdtypes.html#str) = 'GET', headers: Mapping[[str](https://docs.python.org/3/library/stdtypes.html#str), Any] | Mapping[[bytes](https://docs.python.org/3/library/stdtypes.html#bytes), Any] | Iterable[[tuple](https://docs.python.org/3/library/stdtypes.html#tuple)[[str](https://docs.python.org/3/library/stdtypes.html#str) | [bytes](https://docs.python.org/3/library/stdtypes.html#bytes), Any]] | [None](https://docs.python.org/3/library/constants.html#None) = None, body: [bytes](https://docs.python.org/3/library/stdtypes.html#bytes) | [str](https://docs.python.org/3/library/stdtypes.html#str) | [None](https://docs.python.org/3/library/constants.html#None) = None, cookies: CookiesT | [None](https://docs.python.org/3/library/constants.html#None) = None, meta: [dict](https://docs.python.org/3/library/stdtypes.html#dict)[[str](https://docs.python.org/3/library/stdtypes.html#str), Any] | [None](https://docs.python.org/3/library/constants.html#None) = None, encoding: [str](https://docs.python.org/3/library/stdtypes.html#str) | [None](https://docs.python.org/3/library/constants.html#None) = None, priority: [int](https://docs.python.org/3/library/functions.html#int) = 0, dont_filter: [bool](https://docs.python.org/3/library/functions.html#bool) = False, errback: Callable[[Failure], Any] | [None](https://docs.python.org/3/library/constants.html#None) = None, cb_kwargs: [dict](https://docs.python.org/3/library/stdtypes.html#dict)[[str](https://docs.python.org/3/library/stdtypes.html#str), Any] | [None](https://docs.python.org/3/library/constants.html#None) = None, flags: [list](https://docs.python.org/3/library/stdtypes.html#list)[[str](https://docs.python.org/3/library/stdtypes.html#str)] | [None](https://docs.python.org/3/library/constants.html#None) = None) → [Request](#scrapy.Request)

Return a [`Request`](#scrapy.Request) instance to follow a link `url`.
It accepts the same arguments as `Request.__init__()` method,
but `url` can be not only an absolute URL, but also

* a relative URL
* a [`Link`](link-extractors.md#scrapy.link.Link) object, e.g. the result of
  [Link Extractors](link-extractors.md#topics-link-extractors)
* a [`Selector`](selectors.md#scrapy.Selector) object for a `<link>` or `<a>` element, e.g.
  `response.css('a.my_link')[0]`
* an attribute [`Selector`](selectors.md#scrapy.Selector) (not SelectorList), e.g.
  `response.css('a::attr(href)')[0]` or
  `response.xpath('//img/@src')[0]`

See [A shortcut for creating Requests](../intro/tutorial.md#response-follow-example) for usage examples.

#### follow_all(urls: Iterable[[str](https://docs.python.org/3/library/stdtypes.html#str) | [Link](link-extractors.md#scrapy.link.Link)] | parsel.SelectorList[Any] | [None](https://docs.python.org/3/library/constants.html#None) = None, callback: CallbackT | [None](https://docs.python.org/3/library/constants.html#None) = None, method: [str](https://docs.python.org/3/library/stdtypes.html#str) = 'GET', headers: Mapping[[str](https://docs.python.org/3/library/stdtypes.html#str), Any] | Mapping[[bytes](https://docs.python.org/3/library/stdtypes.html#bytes), Any] | Iterable[[tuple](https://docs.python.org/3/library/stdtypes.html#tuple)[[str](https://docs.python.org/3/library/stdtypes.html#str) | [bytes](https://docs.python.org/3/library/stdtypes.html#bytes), Any]] | [None](https://docs.python.org/3/library/constants.html#None) = None, body: [bytes](https://docs.python.org/3/library/stdtypes.html#bytes) | [str](https://docs.python.org/3/library/stdtypes.html#str) | [None](https://docs.python.org/3/library/constants.html#None) = None, cookies: CookiesT | [None](https://docs.python.org/3/library/constants.html#None) = None, meta: [dict](https://docs.python.org/3/library/stdtypes.html#dict)[[str](https://docs.python.org/3/library/stdtypes.html#str), Any] | [None](https://docs.python.org/3/library/constants.html#None) = None, encoding: [str](https://docs.python.org/3/library/stdtypes.html#str) | [None](https://docs.python.org/3/library/constants.html#None) = None, priority: [int](https://docs.python.org/3/library/functions.html#int) = 0, dont_filter: [bool](https://docs.python.org/3/library/functions.html#bool) = False, errback: Callable[[Failure], Any] | [None](https://docs.python.org/3/library/constants.html#None) = None, cb_kwargs: [dict](https://docs.python.org/3/library/stdtypes.html#dict)[[str](https://docs.python.org/3/library/stdtypes.html#str), Any] | [None](https://docs.python.org/3/library/constants.html#None) = None, flags: [list](https://docs.python.org/3/library/stdtypes.html#list)[[str](https://docs.python.org/3/library/stdtypes.html#str)] | [None](https://docs.python.org/3/library/constants.html#None) = None, css: [str](https://docs.python.org/3/library/stdtypes.html#str) | [None](https://docs.python.org/3/library/constants.html#None) = None, xpath: [str](https://docs.python.org/3/library/stdtypes.html#str) | [None](https://docs.python.org/3/library/constants.html#None) = None) → Iterable[[Request](#scrapy.Request)]

A generator that produces [`Request`](#scrapy.Request) instances to follow all
links in `urls`. It accepts the same arguments as the [`Request`](#scrapy.Request)’s
`__init__()` method, except that each `urls` element does not need to be
an absolute URL, it can be any of the following:

* a relative URL
* a [`Link`](link-extractors.md#scrapy.link.Link) object, e.g. the result of
  [Link Extractors](link-extractors.md#topics-link-extractors)
* a [`Selector`](selectors.md#scrapy.Selector) object for a `<link>` or `<a>` element, e.g.
  `response.css('a.my_link')[0]`
* an attribute [`Selector`](selectors.md#scrapy.Selector) (not SelectorList), e.g.
  `response.css('a::attr(href)')[0]` or
  `response.xpath('//img/@src')[0]`

In addition, `css` and `xpath` arguments are accepted to perform the link extraction
within the `follow_all()` method (only one of `urls`, `css` and `xpath` is accepted).

Note that when passing a `SelectorList` as argument for the `urls` parameter or
using the `css` or `xpath` parameters, this method will not produce requests for
selectors from which links cannot be obtained (for instance, anchor tags without an
`href` attribute)

> [!NOTE]
> ### See also
> 
> [`Response.follow_all()`](#scrapy.http.Response.follow_all), for a caution about mutable
> *meta* and *cb_kwargs* values.

#### json()

Deserialize a JSON document to a Python object.

> [!WARNING]
> Changed in version 2.18.0: Bodies that cannot be decoded as UTF-8, UTF-16 or UTF-32, as the
> JSON specification requires, are now decoded using
> [`TextResponse.encoding`](#scrapy.http.TextResponse.encoding) instead of raising
> [`UnicodeDecodeError`](https://docs.python.org/3/library/exceptions.html#UnicodeDecodeError).

The result is cached after the first call.

#### urljoin(url)

Constructs an absolute url by combining the Response’s base url with
a possible relative url. The base url shall be extracted from the
`<base>` tag, or just [`Response.url`](#scrapy.http.Response.url) if there is no such
tag.

### HtmlResponse objects

### *class* scrapy.http.HtmlResponse([...]url,)

The [`HtmlResponse`](#scrapy.http.HtmlResponse) class is a subclass of [`TextResponse`](#scrapy.http.TextResponse)
which adds encoding auto-discovering support by looking into the HTML [meta
http-equiv](https://www.w3schools.com/TAGS/att_meta_http_equiv.asp) attribute.  See [`TextResponse.encoding`](#scrapy.http.TextResponse.encoding).

### XmlResponse objects

### *class* scrapy.http.XmlResponse([...]url,)

The [`XmlResponse`](#scrapy.http.XmlResponse) class is a subclass of [`TextResponse`](#scrapy.http.TextResponse) which
adds encoding auto-discovering support by looking into the XML declaration
line.  See [`TextResponse.encoding`](#scrapy.http.TextResponse.encoding).

### JsonResponse objects

### *class* scrapy.http.JsonResponse([...]url,)

The [`JsonResponse`](#scrapy.http.JsonResponse) class is a subclass of [`TextResponse`](#scrapy.http.TextResponse)
that is used when the response has a [JSON MIME type](https://mimesniff.spec.whatwg.org/#json-mime-type) in its Content-Type
header.

## Other functions related to responses

### scrapy.utils.response.response_from_dict(d: [dict](https://docs.python.org/3/library/stdtypes.html#dict)[[str](https://docs.python.org/3/library/stdtypes.html#str), Any]) → [Response](#scrapy.http.Response)

Return a response built from the *d* dict, as returned by
[`Response.to_dict()`](#scrapy.http.Response.to_dict).

> [!WARNING]
> Added in version 2.19.0.

If *d* does not indicate a response class, e.g. because it comes from a
plain [`Response`](#scrapy.http.Response) object or predates [`to_dict()`](#scrapy.http.Response.to_dict),
the class is guessed with `responsetypes`.
