scrapy/scrapy/trunk/docs/ref/request-response.rst

15 KiB

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

Request and Response objects

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

Unknown directive type "module".

.. module:: scrapy.http
   :synopsis: Classes dealing with HTTP requests and responses.

Quick overview

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

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".

Typically, :class:`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 goes back to the spider that generated the request.

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

Unknown interpreted text role "class".

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

Unknown interpreted text role "class".

Both Request and Response classes contains subclasses which adds additional functionality not required in the base classes. See :ref:`ref-request-subclasses` and :ref:`ref-response-subclasses` below.

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

Unknown interpreted text role "ref".

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

Unknown interpreted text role "ref".

Request objects

A :class:`Request` object represents an HTTP request, which is usually generated in the Spider and executed by the Downloader, and thus generating a :class:`Response`.

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

Unknown interpreted text role "class".

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

Unknown interpreted text role "class".

url is a string containing the URL for this request

callback is a function that will be called with the response of this request (once its downloaded) as its first parameter. For more information see :ref:`ref-request-callbacks` below.

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

Unknown interpreted text role "ref".

method is a string with the HTTP method of this request

meta is a dict containing the initial values for the :attr:`Request.meta` attribute. If passed, the dict will be shallow copied.

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

Unknown interpreted text role "attr".

body is a str or unicode containing the request body. If body is a unicode it's encoded to str using the encoding passed. If body is None, an empty string is stored. In any case, the final stored value will be a string (never unicode, never None).

headers is a multi-valued dict containing the headers of this request

cookies is a dict containing the request cookies. Example:

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

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. However, if, for some reason, you want to avoid merging with existing cookies you can instruct Scrapy to do so by setting the dont_merge_cookies item in the Request.meta.

Example of request without merging cookies:

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

encoding is a string with the encoding of this request. This encoding will be used to percent-encode the URL and to convert the body to str (when given as unicode).

dont_filter is a boolean which indicates that this request should not be filtered by the scheduler. This is used when you want to perform an identical request multiple times, for whatever reason

Request Attributes

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

Unknown directive type "attribute".

.. 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 constructor.

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

Unknown directive type "attribute".

.. attribute:: Request.method

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

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

Unknown directive type "attribute".

.. attribute:: Request.headers

    A dictionary-like object which contains the request headers.

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

Unknown directive type "attribute".

.. attribute:: Request.body

    A str that contains the request body

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

Unknown directive type "attribute".

.. attribute:: Request.meta

    A dict that contains arbitrary metadata for this request. This dict is
    empty for new Requests, and is usually  populated by different Scrapy
    components (extensions, middlewares, etc). So the data contained in this
    dict depends on the extensions you have enabled.

    This dict is `shallow copied`_ when the request is cloned using the
    ``copy()`` or ``replace()`` methods.

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

Unknown directive type "attribute".

.. attribute:: Request.cache

    A dict that contains arbitrary cached data for this request. This dict is
    empty for new Requests, and is usually populated by different Scrapy
    components (extensions, middlewares, etc) to avoid duplicate processing. So
    the data contained in this dict depends on the extensions you have enabled.

    Unlike the ``meta`` attribute, this dict is not copied at all when the
    request is cloned using the ``copy()`` or ``replace()`` methods.

Request Methods

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

Unknown directive type "method".

.. method:: Request.copy()

   Return a new Request which is a copy of this Request. The attribute
   :attr:`Request.meta` is copied, while :attr:`Request.cache` is not.

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

Unknown directive type "method".

.. method:: Request.replace()

   Return a Request object with the same members, except for those members
   given new values by whichever keyword arguments are specified. The attribute
   :attr:`Request.meta` is copied, while :attr:`Request.cache` is not.

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

Unknown directive type "method".

.. method:: Request.httprepr()

   Return a string with the raw HTTP representation of this response.

Passing arguments to callback functions

The callback of a request is a function that will be called when the response of that request is downloaded. The callback function will be called with the :class:`Response` object downloaded as its first argument.

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

Unknown interpreted text role "class".

Example:

def parse_page1(self, response):
    request = Request("http://www.example.com/some_page.html",
                      callback=self.parse_page2)

def parse_page2(self, response):
    # this would log http://www.example.com/some_page.html
    self.log("Visited %s" % response.url)

In some cases you may be interested in passing arguments to those callback functions so you can receive those arguments later, when the response is downloaded. There are two ways for doing this:

  1. using a lambda function (or any other function/callable)

  2. using the :attr:`Request.meta` attribute.

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

    Unknown interpreted text role "attr".

Here's an example of logging the referer URL of each page using each mechanism. Keep in mind, however, that the referer URL could be accessed easier via response.request.url).

Using lambda function:

def parse_page1(self, response):
    myarg = response.url
    request = Request("http://www.example.com/some_page.html",
                      callback=lambda r: self.parse_page2(r, myarg))

def parse_page2(self, response, referer_url):
    self.log("Visited page %s from %s" % (response.url, arg))

Using Request.meta:

def parse_page1(self, response):
    request = Request("http://www.example.com/some_page.html",
                      callback=lambda r: self.parse_page2(r, myarg))
    request.meta['referer_url'] = response.url

def parse_page2(self, response):
    self.log("Visited page %s from %s" % (response.url, request.meta['referer_url']))

Request subclasses

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

FormRequest objects

The FormRequest class adds a new parameter to the constructor:

formdata - a dictionary or list of (key, value) tuples (typically
containing HTML Form data) which will be urlencoded and assigned to the body of the request.

For example, if you want to simulate a HTTP Form POST in your spider which sends a coupe of of key-values you would return a :class:`FormRequest` object (from your spider) like this:

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

Unknown interpreted text role "class".
return [FormRequest(url="http://www.example.com/post/action",
                    formdata={'name': 'John Doe', age: '27'})]

Response objects

A :class:`Response` object represents an HTTP response, which is usually downloaded (by the Downloader) and fed to the Spiders for processing.

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

Unknown interpreted text role "class".

url is a string containing the URL for this response

headers is a multivalued dict of the response headers

status is an integer with the HTTP status of the response

body is a str with the response body. It must be str, not unicode, unless you're using a Response sublcass such as :class:`TextResponse`.

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

Unknown interpreted text role "class".

meta is a dict containing the initial values for the :attr:`Response.meta` attribute. If passed, the dict will be shallow copied.

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

Unknown interpreted text role "attr".

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

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

Unknown interpreted text role "attr".

Response Attributes

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

Unknown directive type "attribute".

.. attribute:: Response.url

    A string containing the URL of the response.

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

Unknown directive type "attribute".

.. attribute:: Response.status

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

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

Unknown directive type "attribute".

.. attribute:: Response.headers

    A dictionary-like object which contains the response headers.

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

Unknown directive type "attribute".

.. attribute:: Response.body

    A str containing the body of this Response. Keep in mind that Reponse.body
    is always a str. If you want the unicode version use
    :meth:`TextResponse.body_as_unicode` (only available in
    :class:`TextResponse` and subclasses).

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

Unknown directive type "attribute".

.. attribute:: Response.request

    The :class:`Request` object that generated this response. This attribute is
    assigned in the Scrapy engine, after the response and request has passed
    through all :ref:`Downloader Middlewares <topics-downloader-middleware>`.
    In particular, this means that:

    - HTTP redirections will cause the original request (to the URL before
      redirection) to be assigned to the redirected response (with the final
      URL after redirection).

    - Response.request.url doesn't always equals 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.

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

Unknown directive type "attribute".

.. attribute:: Response.meta

    A dict that contains arbitrary metadata for this response, similar to the
    :attr:`Request.meta` attribute. See the :attr:`Request.meta` attribute for
    more info.

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

Unknown directive type "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.

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

Unknown directive type "attribute".

.. attribute:: Response.cache

    A dict that contains arbitrary cached data for this response, similar to
    the :attr:`Request.cache` attribute. See the :attr:`Request.cache`
    attribute for more info.

Response Methods

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

Unknown directive type "method".

.. method:: Response.copy()

   Return a new Response which is a copy of this Response. The attribute
   :attr:`Response.meta` is copied, while :attr:`Response.cache` is not.

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

Unknown directive type "method".

.. method:: Response.replace(url=None, status=None, headers=None, body=None)

   Return 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, while :attr:`Response.cache` is not.

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

Unknown directive type "method".

.. method:: Response.httprepr()

   Return a string with the raw HTTP representation of this response.

Response subclasses

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

The TextResponse class adds encoding capabilities to the base Response class. The base Response class is intended for binary data such as images or media files.

:class:`TextResponse` supports the following constructor arguments, attributes nd methods in addition to the base Request ones. The remaining functionality is the same as for the :class:`Response` class and is not documented here.

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

Unknown interpreted text role "class".

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

Unknown interpreted text role "class".

TextResponse

TextResponse constructor arguments

  • encoding - a string which contains the encoding to use for this

    TextResponse. If you create a TextResponse with a unicode body it will be encoded using this encoding (remember the body attribute is always a string).

    If encoding is None the encoding will be looked up in the headers anb body instead.

    It defaults to None.

TextResponse attributes

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

Unknown directive type "attribute".

.. attribute:: TextResponse.encoding

   A string with the encoding of this Response. The encoding is resolved in the
   following order:

   1. the encoding passed in the constructor `encoding` argument
   2. the encoding declared in the Content-Type HTTP header
   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.

TextResponse methods

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

Unknown directive type "method".

.. method:: TextResponse.headers_encoding()

    Returns a string with the encoding declared in the headers (ie. the
    Content-Type HTTP header).

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

Unknown directive type "method".

.. method:: TextResponse.body_encoding()

    Returns a string with the encoding of the body, either declared or inferred
    from its contents. The body encoding declaration is implemented in
    :class:`TextResponse` subclasses such as: :class:`HtmlResponse` or
    :class:`XmlResponse`.

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

Unknown directive type "method".

.. method:: TextResponse.body_as_unicode()

    Returns the body of the response as unicode. This is equivalent to::

        response.body.encode(response.encoding)

    But keep in mind that this is not equivalent to::

        unicode(response.body)

    Since in the latter case you would be using you system default encoding
    (typically `ascii`) to convert the body to uniode instead of the response
    encoding.

HtmlResponse objects

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

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

Unknown interpreted text role "class".

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

Unknown interpreted text role "attr".

XmlResponse objects

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

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

Unknown interpreted text role "class".

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

Unknown interpreted text role "attr".
</html>