scrapy/docs/topics/request-response.rst

49 KiB

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> </head>

Requests and Responses

System Message: ERROR/3 (<stdin>, line 7)

Unknown directive type "module".

.. module:: scrapy.http
   :synopsis: Request and Response classes

Scrapy uses :class:`~scrapy.Request` and :class:`Response` objects for crawling web sites.

System Message: ERROR/3 (<stdin>, line 10); backlink

Unknown interpreted text role "class".

System Message: ERROR/3 (<stdin>, line 10); backlink

Unknown interpreted text role "class".

Typically, :class:`~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 :class:`Response` object which travels back to the spider that issued the request.

System Message: ERROR/3 (<stdin>, line 13); backlink

Unknown interpreted text role "class".

System Message: ERROR/3 (<stdin>, line 13); backlink

Unknown interpreted text role "class".

Both :class:`~scrapy.Request` and :class:`Response` classes have subclasses which add functionality not required in the base classes. These are described below in :ref:`topics-request-response-ref-request-subclasses` and :ref:`topics-request-response-ref-response-subclasses`.

System Message: ERROR/3 (<stdin>, line 18); backlink

Unknown interpreted text role "class".

System Message: ERROR/3 (<stdin>, line 18); backlink

Unknown interpreted text role "class".

System Message: ERROR/3 (<stdin>, line 18); backlink

Unknown interpreted text role "ref".

System Message: ERROR/3 (<stdin>, line 18); backlink

Unknown interpreted text role "ref".

Request objects

System Message: ERROR/3 (<stdin>, line 27)

Unknown directive type "autoclass".

.. autoclass:: scrapy.Request

    :param url: the URL of this request

        If the URL is invalid, a :exc:`ValueError` exception is raised.
    :type url: str

    :param callback: sets :attr:`callback`, defaults to ``None``.
    :type callback: Callable[Concatenate[Response, ...], Any] | None

    :param method: the HTTP method of this request. Defaults to ``'GET'``.
    :type method: str

    :param meta: the initial values for the :attr:`.Request.meta` attribute. If
       given, the dict passed in this parameter will be shallow copied.
    :type meta: dict

    :param body: 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``).
    :type body: bytes or str

    :param headers: 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
           :ref:`cookies-mw`. If you need to set cookies for a request, use the
           ``cookies`` argument. This is a known current limitation that is being
           worked on.

    :type headers: dict

    :param cookies: the request cookies. These can be sent in two forms.

        .. invisible-code-block: python

            from scrapy import Request

        1. Using a dict:

        .. code-block:: python

            request_with_cookies = Request(
                url="http://www.example.com",
                cookies={"currency": "USD", "country": "UY"},
            )

        2. Using a list of dicts:

        .. code-block:: python

            request_with_cookies = Request(
                url="https://www.example.com",
                cookies=[
                    {
                        "name": "currency",
                        "value": "USD",
                        "domain": "example.com",
                        "path": "/currency",
                        "secure": True,
                    },
                ],
            )

        The latter form allows for customizing the ``domain`` and ``path``
        attributes of the cookie. This is only useful if the cookies are saved
        for later requests.

        .. reqmeta:: dont_merge_cookies

        When some site returns cookies (in a response) those are stored in the
        cookies for that domain and will be sent again in future requests.
        That's the typical behaviour of any regular web browser.

        Note that setting the :reqmeta:`dont_merge_cookies` key to ``True`` in
        :attr:`request.meta <scrapy.Request.meta>` causes custom cookies to be
        ignored.

        For more info see :ref:`cookies-mw`.

        .. caution:: Cookies set via the ``Cookie`` header are not considered by the
            :ref:`cookies-mw`. If you need to set cookies for a request, use the
            :class:`scrapy.Request.cookies <scrapy.Request>` parameter. This is a known
            current limitation that is being worked on.

    :type cookies: dict or list

    :param encoding: 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
       :reqmeta:`verbatim_url` request meta key.
    :type encoding: str

    :param priority: sets :attr:`priority`, defaults to ``0``.
    :type priority: int

    :param dont_filter: sets :attr:`dont_filter`, defaults to ``False``.
    :type dont_filter: bool

    :param errback: sets :attr:`errback`, defaults to ``None``.
    :type errback: Callable[[Failure], Any] | None

    :param flags:  Flags sent to the request, can be used for logging or similar purposes.
    :type flags: list

    :param cb_kwargs: A dict with arbitrary data that will be passed as keyword arguments to the Request's callback.
    :type cb_kwargs: dict

    .. attribute:: Request.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 :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
        :meth:`replace`.

    .. attribute:: Request.method

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

    .. attribute:: Request.headers

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

    .. attribute:: Request.body

        The request body as bytes.

        This attribute is read-only. To change the body of a Request use
        :meth:`replace`.

    .. autoattribute:: callback

    .. autoattribute:: errback

    .. autoattribute:: priority

    .. attribute:: Request.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
        :class:`~scrapy.http.Response` object as argument.

        This dict is :doc:`shallow copied <library/copy>` 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 :ref:`errback-cb_kwargs`.

        .. note:: When :setting:`JOBDIR` is set, requests are serialized to disk
            with :mod:`pickle` (see :ref:`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.

    .. attribute:: Request.meta
       :value: {}

        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
        :attr:`~scrapy.http.Response.meta` attribute of a response.

        To pass your own data from one spider callback to another, use
        :attr:`cb_kwargs` instead, see :ref:`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`` to ``True``,
        :class:`~scrapy.downloadermiddlewares.retry.RetryMiddleware` will never
        retry that request, even if it fails. See :ref:`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,
        :class:`~scrapy.downloadermiddlewares.retry.RetryMiddleware` uses the
        ``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`` 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 :ref:`downloader middleware
        <topics-downloader-middleware>` method.

        Also mind that the :meth:`copy` and :meth:`replace` request methods
        :doc:`shallow-copy <library/copy>` request metadata.

        .. seealso:: :class:`~scrapy.spidermiddlewares.metacopy.MetaCopyDetectionMiddleware`
            for a built-in middleware that warns about this issue at run time.

    .. autoattribute:: dont_filter

    .. autoattribute:: Request.attributes

    .. method:: Request.copy()

       Return a new Request which is a copy of this Request. See also:
       :ref:`callback-data`.

    .. method:: Request.replace([url, method, headers, body, cookies, meta, flags, encoding, priority, dont_filter, callback, errback, cb_kwargs, cls])

       Return a Request object with the same members, except for those members
       given new values by whichever keyword arguments are specified. The
       :attr:`~scrapy.Request.cb_kwargs` and :attr:`~scrapy.Request.meta` attributes are shallow
       copied by default (unless new values are given as arguments). See also
       :ref:`callback-data`.

    .. automethod:: from_curl

    .. automethod:: to_curl

    .. automethod:: to_dict


Creating requests that submit HTML forms

Use :doc:`form2request <form2request:index>` to build request data from an HTML <form> element and convert it to a :class:`~scrapy.Request`.

System Message: ERROR/3 (<stdin>, line 274); backlink

Unknown interpreted text role "doc".

System Message: ERROR/3 (<stdin>, line 274); backlink

Unknown interpreted text role "class".

Install it with pip:

System Message: WARNING/2 (<stdin>, line 279)

Cannot analyze code. Pygments package not found.

.. code-block:: bash

    pip install form2request

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

System Message: WARNING/2 (<stdin>, line 286)

Cannot analyze code. Pygments package not found.

.. code-block:: 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:

System Message: WARNING/2 (<stdin>, line 303)

Cannot analyze code. Pygments package not found.

.. code-block:: python

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

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:

System Message: WARNING/2 (<stdin>, line 320)

Cannot analyze code. Pygments package not found.

.. code-block:: 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): ...


Request fingerprints

There are some aspects of scraping, such as filtering out duplicate requests (see :setting:`DUPEFILTER_CLASS`) or caching responses (see :setting:`HTTPCACHE_POLICY`), where you need the ability to generate a short, unique identifier from a :class:`~scrapy.Request` object: a request fingerprint.

System Message: ERROR/3 (<stdin>, line 356); backlink

Unknown interpreted text role "setting".

System Message: ERROR/3 (<stdin>, line 356); backlink

Unknown interpreted text role "setting".

System Message: ERROR/3 (<stdin>, line 356); backlink

Unknown interpreted text role "class".

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 :setting:`REQUEST_FINGERPRINTER_CLASS` setting.

System Message: ERROR/3 (<stdin>, line 371); backlink

Unknown interpreted text role "setting".

System Message: ERROR/3 (<stdin>, line 374)

Unknown directive type "setting".

.. setting:: REQUEST_FINGERPRINTER_CLASS

REQUEST_FINGERPRINTER_CLASS

Default: :class:`scrapy.utils.request.RequestFingerprinter`

System Message: ERROR/3 (<stdin>, line 379); backlink

Unknown interpreted text role "class".

A :ref:`request fingerprinter class <custom-request-fingerprinter>` or its import path.

System Message: ERROR/3 (<stdin>, line 381); backlink

Unknown interpreted text role "ref".

System Message: ERROR/3 (<stdin>, line 384)

Unknown directive type "autoclass".

.. autoclass:: scrapy.utils.request.RequestFingerprinter

Writing your own request fingerprinter

A request fingerprinter is a :ref:`component <topics-components>` that must implement the following method:

System Message: ERROR/3 (<stdin>, line 391); backlink

Unknown interpreted text role "ref".

System Message: ERROR/3 (<stdin>, line 394)

Unknown directive type "currentmodule".

.. currentmodule:: None

System Message: ERROR/3 (<stdin>, line 396)

Unknown directive type "method".

.. method:: fingerprint(self, request: scrapy.Request)

   Return a :class:`bytes` object that uniquely identifies *request*.

   See also :ref:`request-fingerprint-restrictions`.

System Message: ERROR/3 (<stdin>, line 402)

Unknown directive type "currentmodule".

.. currentmodule:: scrapy.http

The :meth:`fingerprint` method of the default request fingerprinter, :class:`scrapy.utils.request.RequestFingerprinter`, uses :func:`scrapy.utils.request.fingerprint` with its default parameters. For some common use cases you can use :func:`scrapy.utils.request.fingerprint` as well in your :meth:`fingerprint` method implementation:

System Message: ERROR/3 (<stdin>, line 404); backlink

Unknown interpreted text role "meth".

System Message: ERROR/3 (<stdin>, line 404); backlink

Unknown interpreted text role "class".

System Message: ERROR/3 (<stdin>, line 404); backlink

Unknown interpreted text role "func".

System Message: ERROR/3 (<stdin>, line 404); backlink

Unknown interpreted text role "func".

System Message: ERROR/3 (<stdin>, line 404); backlink

Unknown interpreted text role "meth".

System Message: ERROR/3 (<stdin>, line 410)

Unknown directive type "autofunction".

.. autofunction:: scrapy.utils.request.fingerprint

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

System Message: ERROR/3 (<stdin>, line 412); backlink

Unknown interpreted text role "reqmeta".

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

System Message: WARNING/2 (<stdin>, line 420)

Cannot analyze code. Pygments package not found.

.. code-block:: 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 :func:`scrapy.utils.request.fingerprint`, make sure you use :class:`~weakref.WeakKeyDictionary` to cache request fingerprints:

System Message: ERROR/3 (<stdin>, line 435); backlink

Unknown interpreted text role "func".

System Message: ERROR/3 (<stdin>, line 435); backlink

Unknown interpreted text role "class".
  • 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 :class:`~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.

    System Message: ERROR/3 (<stdin>, line 442); backlink

    Unknown interpreted text role "class".

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:

System Message: WARNING/2 (<stdin>, line 449)

Cannot analyze code. Pygments package not found.

.. code-block:: 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 :attr:`request.meta <scrapy.Request.meta>` when available, and then falls back to :func:`scrapy.utils.request.fingerprint`. For example:

System Message: ERROR/3 (<stdin>, line 467); backlink

Unknown interpreted text role "attr".

System Message: ERROR/3 (<stdin>, line 467); backlink

Unknown interpreted text role "func".

System Message: WARNING/2 (<stdin>, line 473)

Cannot analyze code. Pygments package not found.

.. code-block:: 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:

System Message: WARNING/2 (<stdin>, line 487)

Cannot analyze code. Pygments package not found.

.. code-block:: 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]


Request fingerprint restrictions

Scrapy components that use request fingerprints may impose additional restrictions on the format of the fingerprints that your :ref:`request fingerprinter <custom-request-fingerprinter>` generates.

System Message: ERROR/3 (<stdin>, line 514); backlink

Unknown interpreted text role "ref".

The following built-in Scrapy components have such restrictions:

  • :class:`scrapy.extensions.httpcache.FilesystemCacheStorage` (default value of :setting:`HTTPCACHE_STORAGE`)

    System Message: ERROR/3 (<stdin>, line 520); backlink

    Unknown interpreted text role "class".

    System Message: ERROR/3 (<stdin>, line 520); backlink

    Unknown interpreted text role "setting".

    Request fingerprints must be at least 1 byte long.

    Path and filename length limits of the file system of :setting:`HTTPCACHE_DIR` also apply. Inside :setting:`HTTPCACHE_DIR`, the following directory structure is created:

    System Message: ERROR/3 (<stdin>, line 525); backlink

    Unknown interpreted text role "setting".

    System Message: ERROR/3 (<stdin>, line 525); backlink

    Unknown interpreted text role "setting".

    • :attr:`.Spider.name`

      System Message: ERROR/3 (<stdin>, line 529); backlink

      Unknown interpreted text role "attr".

      • 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), :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:

    System Message: ERROR/3 (<stdin>, line 537); backlink

    Unknown interpreted text role "setting".

    /home/user/project/.scrapy/httpcache/my_spider/01/0123456789abcdef0123456789abcdef01234567/response_headers
    
  • :class:`scrapy.extensions.httpcache.DbmCacheStorage`

    System Message: ERROR/3 (<stdin>, line 544); backlink

    Unknown interpreted text role "class".

    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.

Callbacks

A callback is a function that Scrapy calls with the :class:`Response` of a :class:`~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:

System Message: ERROR/3 (<stdin>, line 557); backlink

Unknown interpreted text role "class".

System Message: ERROR/3 (<stdin>, line 557); backlink

Unknown interpreted text role "class".

System Message: WARNING/2 (<stdin>, line 562)

Cannot analyze code. Pygments package not found.

.. code-block:: 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 :ref:`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.

System Message: ERROR/3 (<stdin>, line 580); backlink

Unknown interpreted text role "ref".

Assigning a callback to a request

To assign a callback to a request, use the callback parameter of :class:`~scrapy.Request`, which sets the :attr:`.Request.callback` attribute:

System Message: ERROR/3 (<stdin>, line 591); backlink

Unknown interpreted text role "class".

System Message: ERROR/3 (<stdin>, line 591); backlink

Unknown interpreted text role "attr".

System Message: WARNING/2 (<stdin>, line 594)

Cannot analyze code. Pygments package not found.

.. code-block:: 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 :attr:`~scrapy.Request.callback` set to None, are handled by the :meth:`~scrapy.Spider.parse` method of the spider:

System Message: ERROR/3 (<stdin>, line 604); backlink

Unknown interpreted text role "attr".

System Message: ERROR/3 (<stdin>, line 604); backlink

Unknown interpreted text role "meth".

System Message: WARNING/2 (<stdin>, line 607)

Cannot analyze code. Pygments package not found.

.. code-block:: 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 :ref:`component <topics-components>` sends it and handles its response itself, assign the special :func:`~scrapy.http.request.NO_CALLBACK` value to it instead, so that :ref:`downloader middlewares <topics-downloader-middleware>` can tell such requests apart.

System Message: ERROR/3 (<stdin>, line 611); backlink

Unknown interpreted text role "ref".

System Message: ERROR/3 (<stdin>, line 611); backlink

Unknown interpreted text role "func".

System Message: ERROR/3 (<stdin>, line 611); backlink

Unknown interpreted text role "ref".

While :attr:`~scrapy.Request.callback` only accepts callables, some spider classes let you also define a callback by name: both :attr:`CrawlSpider.rules <scrapy.spiders.CrawlSpider.rules>` and :attr:`SitemapSpider.sitemap_rules <scrapy.spiders.SitemapSpider.sitemap_rules>` accept the name of a spider method as a string.

System Message: ERROR/3 (<stdin>, line 617); backlink

Unknown interpreted text role "attr".

System Message: ERROR/3 (<stdin>, line 617); backlink

Unknown interpreted text role "attr".

System Message: ERROR/3 (<stdin>, line 617); backlink

Unknown interpreted text role "attr".

Writing a callback

Any callable can be a callback, as long as it takes the response as its first positional parameter, and any :ref:`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.

System Message: ERROR/3 (<stdin>, line 629); backlink

Unknown interpreted text role "ref".

Note

If you enable :ref:`job persistence <topics-jobs>` through the :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 :ref:`request-serialization`.

System Message: ERROR/3 (<stdin>, line 634); backlink

Unknown interpreted text role "ref".

System Message: ERROR/3 (<stdin>, line 634); backlink

Unknown interpreted text role "setting".

System Message: ERROR/3 (<stdin>, line 634); backlink

Unknown interpreted text role "ref".

A callback can be:

  • A regular function:

    System Message: WARNING/2 (<stdin>, line 644)

    Cannot analyze code. Pygments package not found.

    .. code-block:: python
    
        def parse(self, response):
            return {"url": response.url}
    
    
  • A generator function:

    System Message: WARNING/2 (<stdin>, line 651)

    Cannot analyze code. Pygments package not found.

    .. code-block:: python
    
        def parse(self, response):
            yield {"url": response.url}
    
    
  • A coroutine function, i.e. defined with async def:

    System Message: WARNING/2 (<stdin>, line 658)

    Cannot analyze code. Pygments package not found.

    .. code-block:: python
    
        async def parse(self, response):
            return {"url": response.url}
    
    
  • An asynchronous generator function:

    System Message: WARNING/2 (<stdin>, line 665)

    Cannot analyze code. Pygments package not found.

    .. code-block:: 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 :ref:`topics-coroutines`.

System Message: ERROR/3 (<stdin>, line 670); backlink

Unknown interpreted text role "ref".

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 :class:`~scrapy.Request` object, which Scrapy schedules, downloads and eventually sends to its own callback.

    System Message: ERROR/3 (<stdin>, line 687); backlink

    Unknown interpreted text role "class".

  • An :ref:`item object <topics-items>`, which Scrapy sends to the :ref:`item pipelines <topics-item-pipeline>`.

    System Message: ERROR/3 (<stdin>, line 690); backlink

    Unknown interpreted text role "ref".

    System Message: ERROR/3 (<stdin>, line 690); backlink

    Unknown interpreted text role "ref".

    Any object that is neither None nor a :class:`~scrapy.Request` object is treated as an item.

    System Message: ERROR/3 (<stdin>, line 693); backlink

    Unknown interpreted text role "class".

  • An iterable of any of the values above, e.g. a list or, more commonly, a generator.

    :term:`Asynchronous iterables <asynchronous iterable>`, e.g. an :term:`asynchronous generator`, are also supported.

    System Message: ERROR/3 (<stdin>, line 699); backlink

    Unknown interpreted text role "term".

    System Message: ERROR/3 (<stdin>, line 699); backlink

    Unknown interpreted text role "term".

Note

When a callback returns an object, Scrapy iterates that object if it supports iteration, except for :class:`dict`, :class:`~scrapy.Item`, :class:`str` and :class:`bytes` objects, which are always handled as single items.

System Message: ERROR/3 (<stdin>, line 702); backlink

Unknown interpreted text role "class".

System Message: ERROR/3 (<stdin>, line 702); backlink

Unknown interpreted text role "class".

System Message: ERROR/3 (<stdin>, line 702); backlink

Unknown interpreted text role "class".

System Message: ERROR/3 (<stdin>, line 702); backlink

Unknown interpreted text role "class".

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 :setting:`WARN_ON_GENERATOR_RETURN_VALUE`.

System Message: ERROR/3 (<stdin>, line 707); backlink

Unknown interpreted text role "setting".

Before Scrapy acts on the output of a callback, that output goes through the :meth:`~scrapy.spidermiddlewares.SpiderMiddleware.process_spider_output` method of your :ref:`spider middlewares <topics-spider-middleware>`, which may modify it or drop part of it.

System Message: ERROR/3 (<stdin>, line 712); backlink

Unknown interpreted text role "meth".

System Message: ERROR/3 (<stdin>, line 712); backlink

Unknown interpreted text role "ref".

If a callback raises an exception, the :attr:`~scrapy.Request.errback` of the request is not called. The exception goes through the :meth:`~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 :signal:`spider_error` signal.

System Message: ERROR/3 (<stdin>, line 717); backlink

Unknown interpreted text role "attr".

System Message: ERROR/3 (<stdin>, line 717); backlink

Unknown interpreted text role "meth".

System Message: ERROR/3 (<stdin>, line 717); backlink

Unknown interpreted text role "signal".

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 :attr:`.Request.cb_kwargs` attribute:

System Message: ERROR/3 (<stdin>, line 730); backlink

Unknown interpreted text role "attr".

System Message: WARNING/2 (<stdin>, line 735)

Cannot analyze code. Pygments package not found.

.. code-block:: 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,
        )

:attr:`.Request.cb_kwargs` is the recommended way to pass your own data to a callback. Use :attr:`.Request.meta` only for data aimed at :ref:`components <topics-components>`, such as middlewares and extensions.

System Message: ERROR/3 (<stdin>, line 757); backlink

Unknown interpreted text role "attr".

System Message: ERROR/3 (<stdin>, line 757); backlink

Unknown interpreted text role "attr".

System Message: ERROR/3 (<stdin>, line 757); backlink

Unknown interpreted text role "ref".

Errbacks

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

It receives a :exc:`~twisted.python.failure.Failure` as first parameter and can be used to track connection establishment timeouts, DNS errors etc.

System Message: ERROR/3 (<stdin>, line 770); backlink

Unknown interpreted text role "exc".

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

System Message: WARNING/2 (<stdin>, line 776)

Cannot analyze code. Pygments package not found.

.. code-block:: 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)


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:

System Message: WARNING/2 (<stdin>, line 840)

Cannot analyze code. Pygments package not found.

.. code-block:: 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"],
        )


Request.meta special keys

The :attr:`.Request.meta` attribute can contain any arbitrary data, but there are some special keys recognized by Scrapy and its built-in extensions.

System Message: ERROR/3 (<stdin>, line 870); backlink

Unknown interpreted text role "attr".

Those are:

System Message: ERROR/3 (<stdin>, line 906)

Unknown directive type "reqmeta".

.. reqmeta:: bindaddress

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:

System Message: WARNING/2 (<stdin>, line 923)

Cannot analyze code. Pygments package not found.

.. code-block:: python

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

System Message: WARNING/2 (<stdin>, line 930)

Cannot analyze code. Pygments package not found.

.. code-block:: python

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

If not set, built-in HTTP download handlers use the value of :setting:`DOWNLOAD_BIND_ADDRESS` as the default bind address. Set the :reqmeta:`bindaddress` request meta key to override it for a specific request.

System Message: ERROR/3 (<stdin>, line 937); backlink

Unknown interpreted text role "setting".

System Message: ERROR/3 (<stdin>, line 937); backlink

Unknown interpreted text role "reqmeta".

This meta key is not supported by :class:`~scrapy.core.downloader.handlers._httpx.HttpxDownloadHandler`, but the :setting:`DOWNLOAD_BIND_ADDRESS` is supported by it.

System Message: ERROR/3 (<stdin>, line 942); backlink

Unknown interpreted text role "class".

System Message: ERROR/3 (<stdin>, line 942); backlink

Unknown interpreted text role "setting".

System Message: ERROR/3 (<stdin>, line 946)

Unknown directive type "reqmeta".

.. reqmeta:: download_timeout

download_timeout

The amount of time (in secs) that the downloader will wait before timing out. See also: :setting:`DOWNLOAD_TIMEOUT`.

System Message: ERROR/3 (<stdin>, line 951); backlink

Unknown interpreted text role "setting".

System Message: ERROR/3 (<stdin>, line 954)

Unknown directive type "reqmeta".

.. reqmeta:: download_latency

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.

System Message: ERROR/3 (<stdin>, line 964)

Unknown directive type "reqmeta".

.. reqmeta:: download_fail_on_dataloss

download_fail_on_dataloss

Whether or not to fail on broken responses. See: :setting:`DOWNLOAD_FAIL_ON_DATALOSS`.

System Message: ERROR/3 (<stdin>, line 969); backlink

Unknown interpreted text role "setting".

System Message: ERROR/3 (<stdin>, line 972)

Unknown directive type "reqmeta".

.. reqmeta:: give_up_log_level

give_up_log_level

System Message: ERROR/3 (<stdin>, line 977)

Unknown directive type "versionadded".

.. versionadded:: 2.17.0

:ref:`Logging level <levels>` used for the message logged when a request exceeds its retries. See :setting:`RETRY_GIVE_UP_LOG_LEVEL` for details.

System Message: ERROR/3 (<stdin>, line 979); backlink

Unknown interpreted text role "ref".

System Message: ERROR/3 (<stdin>, line 979); backlink

Unknown interpreted text role "setting".

System Message: ERROR/3 (<stdin>, line 982)

Unknown directive type "reqmeta".

.. reqmeta:: http_auth_domain

http_auth_domain

System Message: ERROR/3 (<stdin>, line 987)

Unknown directive type "versionadded".

.. versionadded:: 2.17.0

Overrides :setting:`HTTPAUTH_DOMAIN` for this request.

System Message: ERROR/3 (<stdin>, line 989); backlink

Unknown interpreted text role "setting".

System Message: ERROR/3 (<stdin>, line 991)

Unknown directive type "reqmeta".

.. reqmeta:: http_pass

http_pass

System Message: ERROR/3 (<stdin>, line 996)

Unknown directive type "versionadded".

.. versionadded:: 2.17.0

Overrides :setting:`HTTPAUTH_PASS` for this request.

System Message: ERROR/3 (<stdin>, line 998); backlink

Unknown interpreted text role "setting".

System Message: ERROR/3 (<stdin>, line 1000)

Unknown directive type "reqmeta".

.. reqmeta:: http_user

http_user

System Message: ERROR/3 (<stdin>, line 1005)

Unknown directive type "versionadded".

.. versionadded:: 2.17.0

Overrides :setting:`HTTPAUTH_USER` for this request.

System Message: ERROR/3 (<stdin>, line 1007); backlink

Unknown interpreted text role "setting".

System Message: ERROR/3 (<stdin>, line 1009)

Unknown directive type "reqmeta".

.. reqmeta:: max_retry_times

max_retry_times

The meta key is used set retry times per request. When set, the :reqmeta:`max_retry_times` meta key takes higher precedence over the :setting:`RETRY_TIMES` setting.

System Message: ERROR/3 (<stdin>, line 1014); backlink

Unknown interpreted text role "reqmeta".

System Message: ERROR/3 (<stdin>, line 1014); backlink

Unknown interpreted text role "setting".

System Message: ERROR/3 (<stdin>, line 1018)

Unknown directive type "reqmeta".

.. reqmeta:: verbatim_url

verbatim_url

System Message: ERROR/3 (<stdin>, line 1023)

Unknown directive type "versionadded".

.. versionadded:: 2.17.0

Set this key to True to keep the request URL as passed to :class:`~scrapy.Request`, without URL percent-encoding.

System Message: ERROR/3 (<stdin>, line 1025); backlink

Unknown interpreted text role "class".

When this key is enabled, :func:`~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.

System Message: ERROR/3 (<stdin>, line 1028); backlink

Unknown interpreted text role "func".

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

Stopping the download of a Response

Raising a :exc:`~scrapy.exceptions.StopDownload` exception from a handler for the :class:`~scrapy.signals.bytes_received` or :class:`~scrapy.signals.headers_received` signals will stop the download of a given response. See the following example:

System Message: ERROR/3 (<stdin>, line 1040); backlink

Unknown interpreted text role "exc".

System Message: ERROR/3 (<stdin>, line 1040); backlink

Unknown interpreted text role "class".

System Message: ERROR/3 (<stdin>, line 1040); backlink

Unknown interpreted text role "class".

System Message: WARNING/2 (<stdin>, line 1044)

Cannot analyze code. Pygments package not found.

.. code-block:: 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 :exc:`~scrapy.exceptions.StopDownload` exception.

System Message: ERROR/3 (<stdin>, line 1078); backlink

Unknown interpreted text role "exc".

Request subclasses

Here is the list of built-in :class:`~scrapy.Request` subclasses. You can also subclass it to implement your own custom functionality.

System Message: ERROR/3 (<stdin>, line 1088); backlink

Unknown interpreted text role "class".

FormRequest

System Message: ERROR/3 (<stdin>, line 1094)

Unknown directive type "autoclass".

.. autoclass:: scrapy.FormRequest

JsonRequest

The JsonRequest class extends the base :class:`~scrapy.Request` class with functionality for dealing with JSON requests.

System Message: ERROR/3 (<stdin>, line 1099); backlink

Unknown interpreted text role "class".

System Message: ERROR/3 (<stdin>, line 1102)

Invalid class attribute value for "class" directive: "JsonRequest(url, [... data, dumps_kwargs])".

.. class:: JsonRequest(url, [... data, dumps_kwargs])

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

   Using the :class:`JsonRequest` will set the ``Content-Type`` header to ``application/json``
   and ``Accept`` header to ``application/json, text/javascript, */*; q=0.01``

   :param data: is any JSON serializable object that needs to be JSON encoded and assigned to body.
      If the :attr:`~scrapy.Request.body` argument is provided this parameter will be ignored.
      If the :attr:`~scrapy.Request.body` argument is not provided and the
      ``data`` argument is provided the :attr:`~scrapy.Request.method` will be
      set to ``'POST'`` automatically.
   :type data: object

   :param dumps_kwargs: Parameters that will be passed to underlying :func:`json.dumps` method which is used to serialize
       data into JSON format.
   :type dumps_kwargs: dict

   .. autoattribute:: JsonRequest.attributes

JsonRequest usage example

Sending a JSON POST request with a JSON payload:

System Message: WARNING/2 (<stdin>, line 1130)

Cannot analyze code. Pygments package not found.

.. code-block:: python

   data = {
       "name1": "value1",
       "name2": "value2",
   }
   yield JsonRequest(url="http://www.example.com/post/action", data=data)


Response objects

System Message: ERROR/3 (<stdin>, line 1142)

Unknown directive type "autoclass".

.. autoclass:: Response

    :param url: the URL of this response
    :type url: str

    :param status: the HTTP status of the response. Defaults to ``200``.
    :type status: int

    :param headers: the headers of this response. The dict values can be strings
       (for single valued headers) or lists (for multi-valued headers).
    :type headers: dict

    :param body: the response body. To access the decoded text as a string, use
       ``response.text`` from an encoding-aware
       :ref:`Response subclass <topics-request-response-ref-response-subclasses>`,
       such as :class:`TextResponse`.
    :type body: bytes

    :param flags: is a list containing the initial values for the
       :attr:`Response.flags` attribute. If given, the list will be shallow
       copied.
    :type flags: list

    :param request: the initial value of the :attr:`Response.request` attribute.
        This represents the :class:`~scrapy.Request` that generated this response.
    :type request: scrapy.Request

    :param certificate: an object representing the server's SSL certificate.
    :type certificate: typing.Any

    :param ip_address: The IP address of the server from which the Response originated.
    :type ip_address: :class:`ipaddress.IPv4Address` or :class:`ipaddress.IPv6Address`

    :param protocol: The protocol that was used to download the response.
        For instance: "HTTP/1.0", "HTTP/1.1", "h2"
    :type protocol: :class:`str`

    .. attribute:: Response.url

        A string containing the URL of the response.

        This attribute is read-only. To change the URL of a Response use
        :meth:`replace`.

    .. attribute:: Response.status

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

    .. attribute:: Response.headers

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

        .. skip: next

        .. code-block:: python

            response.headers.getlist("Set-Cookie")

    .. attribute:: Response.body

        The response body as bytes.

        If you want the body as a string, use :attr:`TextResponse.text` (only
        available in :class:`TextResponse` and subclasses).

        This attribute is read-only. To change the body of a Response use
        :meth:`replace`.

    .. attribute:: Response.request

        The :class:`~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 :ref:`Downloader Middlewares <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
          :ref:`Spider Middlewares <topics-spider-middleware>`, but not in
          Downloader Middlewares (although you have the Request available there by
          other means) and handlers of the :signal:`response_downloaded` signal.

    .. attribute:: Response.meta

        A shortcut to the :attr:`~scrapy.Request.meta` attribute of the
        :attr:`Response.request` object (i.e. ``self.request.meta``).

        Unlike the :attr:`Response.request` attribute, the :attr:`Response.meta`
        attribute is propagated along redirects and retries, so you will get
        the original :attr:`.Request.meta` sent from your spider.

        .. seealso:: :attr:`.Request.meta` attribute

    .. attribute:: Response.cb_kwargs

        A shortcut to the :attr:`~scrapy.Request.cb_kwargs` attribute of the
        :attr:`Response.request` object (i.e. ``self.request.cb_kwargs``).

        Unlike the :attr:`Response.request` attribute, the
        :attr:`Response.cb_kwargs` attribute is propagated along redirects and
        retries, so you will get the original :attr:`.Request.cb_kwargs` sent from your spider.

        .. seealso:: :attr:`.Request.cb_kwargs` attribute

    .. attribute:: Response.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.

    .. attribute:: Response.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.

    .. attribute:: Response.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,
        :attr:`ip_address` is always ``None``.

    .. attribute:: Response.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,
        :attr:`protocol` is always ``None``.

    .. autoattribute:: Response.attributes

    .. method:: Response.copy()

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

    .. method:: Response.replace([url, status, headers, body, request, flags, certificate, ip_address, protocol, cls])

       Returns a Response object with the same members, except for those members
       given new values by whichever keyword arguments are specified. The
       attribute :attr:`Response.meta` is copied by default.

    .. method:: Response.urljoin(url)

        Constructs an absolute url by combining the Response's :attr:`url` with
        a possible relative url.

        This is a wrapper over :func:`~urllib.parse.urljoin`, it's merely an alias for
        making this call:

        .. skip: next

        .. code-block:: python

            urllib.parse.urljoin(response.url, url)

    .. automethod:: Response.follow

    .. automethod:: Response.follow_all


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

System Message: ERROR/3 (<stdin>, line 1330)

Invalid class attribute value for "class" directive: "TextResponse(url, [encoding[, ...]])".

.. class:: TextResponse(url, [encoding[, ...]])

    :class:`TextResponse` objects adds encoding capabilities to the base
    :class:`Response` class, which is meant to be used only for binary data,
    such as images, sounds or any media file.

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

    :param encoding: is a string which contains the encoding to use for this
       response. If you create a :class:`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.
    :type encoding: str

    :class:`TextResponse` objects support the following attributes in addition
    to the standard :class:`Response` ones:

    .. attribute:: TextResponse.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:

            .. code-block:: pycon

                >>> str(b"body")
                "b'body'"


    .. attribute:: TextResponse.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 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.

       3. the encoding declared in the response body. The TextResponse class
          doesn't provide any special functionality for this. However, the
          :class:`HtmlResponse` and :class:`XmlResponse` classes do.

       4. the encoding inferred by looking at the response body. This is the more
          fragile method but also the last one tried.

    .. attribute:: TextResponse.selector

        A :class:`~scrapy.Selector` instance using the response as
        target. The selector is lazily instantiated on first access.

    .. autoattribute:: TextResponse.attributes

    :class:`TextResponse` objects support the following methods in addition to
    the standard :class:`Response` ones:

    .. method:: TextResponse.jmespath(query)

        .. skip: start

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

        .. code-block:: python

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

    .. method:: TextResponse.xpath(query)

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

        .. code-block:: python

            response.xpath("//p")

    .. method:: TextResponse.css(query)

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

        .. code-block:: python

            response.css("p")

        .. skip: end

    .. automethod:: TextResponse.follow

    .. automethod:: TextResponse.follow_all

    .. automethod:: TextResponse.json()

        Returns a Python object from deserialized JSON document.
        The result is cached after the first call.

    .. method:: TextResponse.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 :attr:`Response.url` if there is no such
        tag.



HtmlResponse objects

System Message: ERROR/3 (<stdin>, line 1446)

Invalid class attribute value for "class" directive: "HtmlResponse(url[, ...])".

.. class:: HtmlResponse(url[, ...])

    The :class:`HtmlResponse` class is a subclass of :class:`TextResponse`
    which adds encoding auto-discovering support by looking into the HTML `meta
    http-equiv`_ attribute.  See :attr:`TextResponse.encoding`.

XmlResponse objects

System Message: ERROR/3 (<stdin>, line 1457)

Invalid class attribute value for "class" directive: "XmlResponse(url[, ...])".

.. class:: XmlResponse(url[, ...])

    The :class:`XmlResponse` class is a subclass of :class:`TextResponse` which
    adds encoding auto-discovering support by looking into the XML declaration
    line.  See :attr:`TextResponse.encoding`.

JsonResponse objects

System Message: ERROR/3 (<stdin>, line 1468)

Invalid class attribute value for "class" directive: "JsonResponse(url[, ...])".

.. class:: JsonResponse(url[, ...])

    The :class:`JsonResponse` class is a subclass of :class:`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.
</html>