Requests and Responses

Scrapy uses Request and Response objects for crawling web sites.

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

Both Request and Response classes have subclasses which add functionality not required in the base classes. These are described below in Request subclasses and Response subclasses.

Request objects

class scrapy.http.Request(\args, **kwargs*)[source]

Represents an HTTP request, which is usually generated in a Spider and executed by the Downloader, thus generating a Response.

  • Parameters

    • url (str) –

      the URL of this request

      If the URL is invalid, a ValueError exception is raised.

    • callback (collections.abc.Callable) – the function that will be called with the response of this request (once it’s downloaded) as its first parameter. For more information see Passing additional data to callback functions below. If a Request doesn’t specify a callback, the spider’s parse() method will be used. Note that if exceptions are raised during processing, errback is called instead.

    • method (str) – the HTTP method of this request. Defaults to 'GET'.

    • meta (dict) – the initial values for the Request.meta attribute. If given, the dict passed in this parameter will be shallow copied.

    • body (bytes or 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) –

      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 CookiesMiddleware. If you need to set cookies for a request, use the Request.cookies parameter. This is a known current limitation that is being worked on.

    • cookies (dict or list) –

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

      1. Using a dict:

        1. request_with_cookies = Request(url="http://www.example.com",
        2. cookies={'currency': 'USD', 'country': 'UY'})
      2. Using a list of dicts:

        1. request_with_cookies = Request(url="http://www.example.com",
        2. cookies=[{'name': 'currency',
        3. 'value': 'USD',
        4. 'domain': 'example.com',
        5. 'path': '/currency'}])

      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.

      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.

      To create a request that does not send stored cookies and does not store received cookies, set the dont_merge_cookies key to True in request.meta.

      Example of a request that sends manually-defined cookies and ignores cookie storage:

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

      For more info see CookiesMiddleware.

      Caution

      Cookies set via the Cookie header are not considered by the CookiesMiddleware. If you need to set cookies for a request, use the Request.cookies parameter. This is a known current limitation that is being worked on.

      New in version 2.6.0: Cookie values that are bool, float or int are casted to str.

    • encoding (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).

    • priority (int) – the priority of this request (defaults to 0). The priority is used by the scheduler to define the order used to process requests. Requests with a higher priority value will execute earlier. Negative values are allowed in order to indicate relatively low-priority.

    • dont_filter (bool) – indicates that this request should not be filtered by the scheduler. This is used when you want to perform an identical request multiple times, to ignore the duplicates filter. Use it with care, or you will get into crawling loops. Default to False.

    • errback (collections.abc.Callable) –

      a function that will be called if any exception was raised while processing the request. This includes pages that failed with 404 HTTP errors and such. It receives a Failure as first parameter. For more information, see Using errbacks to catch exceptions in request processing below.

      Changed in version 2.0: The callback parameter is no longer required when the errback parameter is specified.

    • flags (list) – Flags sent to the request, can be used for logging or similar purposes.

    • cb_kwargs (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.

    This attribute is read-only. To change the URL of a Request use 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 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().

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

    See Request.meta special keys for a list of special meta keys recognized by Scrapy.

    This dict is shallow copied when the request is cloned using the copy() or replace() methods, and can also be accessed, in your spider, from the response.meta attribute.

  • 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 object as argument.

    This dict is shallow copied 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.

  • attributes: Tuple[str, …] = (‘url’, ‘callback’, ‘method’, ‘headers’, ‘body’, ‘cookies’, ‘meta’, ‘encoding’, ‘priority’, ‘dont_filter’, ‘errback’, ‘flags’, ‘cb_kwargs’)

    A tuple of 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(), Request.to_dict() and request_from_dict().

  • copy()[source]

    Return a new Request which is a copy of this Request. See also: Passing additional data to callback functions.

  • replace([url, method, headers, body, cookies, meta, flags, encoding, priority, dont_filter, callback, errback, cb_kwargs])[source]

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

  • classmethod from_curl(curl_command: str, ignore_unknown_options: bool = True, \*kwargs*) → RequestTypeVar[source]

    Create a Request object from a string containing a cURL command. It populates the HTTP method, the URL, the headers, the cookies and the body. It accepts the same arguments as the 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() from Request subclasses, such as JSONRequest, or XmlRpcRequest, as well as having downloader middlewares and spider middlewares enabled, such as DefaultHeadersMiddleware, UserAgentMiddleware, or HttpCompressionMiddleware, may modify the Request object.

    To translate a cURL command into a Scrapy request, you may use curl2scrapy.

  • to_dict(**, spider: Optional[Spider] = None*) → dict[source]

    Return a dictionary containing the Request’s data.

    Use request_from_dict() to convert back into a 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.

scrapy.utils.request.request_from_dict(d: dict, **, spider: Optional[Spider] = None*) → Request[source]

Create a 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.

Passing additional data 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 downloaded Response object as its first argument.

Example:

  1. def parse_page1(self, response):
  2. return scrapy.Request("http://www.example.com/some_page.html",
  3. callback=self.parse_page2)
  4. def parse_page2(self, response):
  5. # this would log http://www.example.com/some_page.html
  6. self.logger.info("Visited %s", response.url)

In some cases you may be interested in passing arguments to those callback functions so you can receive the arguments later, in the second callback. The following example shows how to achieve this by using the Request.cb_kwargs attribute:

  1. def parse(self, response):
  2. request = scrapy.Request('http://www.example.com/index.html',
  3. callback=self.parse_page2,
  4. cb_kwargs=dict(main_url=response.url))
  5. request.cb_kwargs['foo'] = 'bar' # add more arguments for the callback
  6. yield request
  7. def parse_page2(self, response, main_url, foo):
  8. yield dict(
  9. main_url=main_url,
  10. other_url=response.url,
  11. foo=foo,
  12. )

Caution

Request.cb_kwargs was introduced in version 1.7. Prior to that, using Request.meta was recommended for passing information around callbacks. After 1.7, Request.cb_kwargs became the preferred way for handling user information, leaving Request.meta for communication with components like middlewares and extensions.

Using errbacks to catch exceptions in request processing

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

It receives a Failure as first parameter and can be used to track connection establishment timeouts, DNS errors etc.

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

  1. import scrapy
  2. from scrapy.spidermiddlewares.httperror import HttpError
  3. from twisted.internet.error import DNSLookupError
  4. from twisted.internet.error import TimeoutError, TCPTimedOutError
  5. class ErrbackSpider(scrapy.Spider):
  6. name = "errback_example"
  7. start_urls = [
  8. "http://www.httpbin.org/", # HTTP 200 expected
  9. "http://www.httpbin.org/status/404", # Not found error
  10. "http://www.httpbin.org/status/500", # server issue
  11. "http://www.httpbin.org:12345/", # non-responding host, timeout expected
  12. "https://example.invalid/", # DNS error expected
  13. ]
  14. def start_requests(self):
  15. for u in self.start_urls:
  16. yield scrapy.Request(u, callback=self.parse_httpbin,
  17. errback=self.errback_httpbin,
  18. dont_filter=True)
  19. def parse_httpbin(self, response):
  20. self.logger.info('Got successful response from {}'.format(response.url))
  21. # do something useful here...
  22. def errback_httpbin(self, failure):
  23. # log all failures
  24. self.logger.error(repr(failure))
  25. # in case you want to do something special for some errors,
  26. # you may need the failure's type:
  27. if failure.check(HttpError):
  28. # these exceptions come from HttpError spider middleware
  29. # you can get the non-200 response
  30. response = failure.value.response
  31. self.logger.error('HttpError on %s', response.url)
  32. elif failure.check(DNSLookupError):
  33. # this is the original request
  34. request = failure.request
  35. self.logger.error('DNSLookupError on %s', request.url)
  36. elif failure.check(TimeoutError, TCPTimedOutError):
  37. request = failure.request
  38. 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:

  1. def parse(self, response):
  2. request = scrapy.Request('http://www.example.com/index.html',
  3. callback=self.parse_page2,
  4. errback=self.errback_page2,
  5. cb_kwargs=dict(main_url=response.url))
  6. yield request
  7. def parse_page2(self, response, main_url):
  8. pass
  9. def errback_page2(self, failure):
  10. yield dict(
  11. main_url=failure.request.cb_kwargs['main_url'],
  12. )

Request.meta special keys

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

Those are:

bindaddress

The IP of the outgoing IP address to use for the performing the request.

download_timeout

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

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.

download_fail_on_dataloss

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

max_retry_times

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

Stopping the download of a Response

Raising a StopDownload exception from a handler for the bytes_received or headers_received signals will stop the download of a given response. See the following example:

  1. import scrapy
  2. class StopSpider(scrapy.Spider):
  3. name = "stop"
  4. start_urls = ["https://docs.scrapy.org/en/latest/"]
  5. @classmethod
  6. def from_crawler(cls, crawler):
  7. spider = super().from_crawler(crawler)
  8. crawler.signals.connect(spider.on_bytes_received, signal=scrapy.signals.bytes_received)
  9. return spider
  10. def parse(self, response):
  11. # 'last_chars' show that the full response was not downloaded
  12. yield {"len": len(response.text), "last_chars": response.text[-40:]}
  13. def on_bytes_received(self, data, request, spider):
  14. raise scrapy.exceptions.StopDownload(fail=False)

which produces the following output:

  1. 2020-05-19 17:26:12 [scrapy.core.engine] INFO: Spider opened
  2. 2020-05-19 17:26:12 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
  3. 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
  4. 2020-05-19 17:26:13 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://docs.scrapy.org/en/latest/> (referer: None) ['download_stopped']
  5. 2020-05-19 17:26:13 [scrapy.core.scraper] DEBUG: Scraped from <200 https://docs.scrapy.org/en/latest/>
  6. {'len': 279, 'last_chars': 'dth, initial-scale=1.0">\n \n <title>Scr'}
  7. 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 exception.

Request subclasses

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

FormRequest objects

The FormRequest class extends the base Request with functionality for dealing with HTML forms. It uses lxml.html forms to pre-populate form fields with form data from Response objects.

class scrapy.http.request.form.FormRequest

class scrapy.http.FormRequest

class scrapy.FormRequest(url[, formdata, ])

The FormRequest class adds a new keyword parameter to the __init__ method. The remaining arguments are the same as for the Request class and are not documented here.

  • Parameters

    formdata (dict or collections.abc.Iterable) – is a dictionary (or iterable of (key, value) tuples) containing HTML Form data which will be url-encoded and assigned to the body of the request.

The FormRequest objects support the following class method in addition to the standard Request methods:

  • classmethod FormRequest.from_response(response[, formname=None, formid=None, formnumber=0, formdata=None, formxpath=None, formcss=None, clickdata=None, dont_click=False, ])

    Returns a new FormRequest object with its form field values pre-populated with those found in the HTML <form> element contained in the given response. For an example see Using FormRequest.from_response() to simulate a user login.

    The policy is to automatically simulate a click, by default, on any form control that looks clickable, like a <input type="submit">. Even though this is quite convenient, and often the desired behaviour, sometimes it can cause problems which could be hard to debug. For example, when working with forms that are filled and/or submitted using javascript, the default from_response() behaviour may not be the most appropriate. To disable this behaviour you can set the dont_click argument to True. Also, if you want to change the control clicked (instead of disabling it) you can also use the clickdata argument.

    Caution

    Using this method with select elements which have leading or trailing whitespace in the option values will not work due to a bug in lxml, which should be fixed in lxml 3.8 and above.

    • Parameters

      • response (Response object) – the response containing a HTML form which will be used to pre-populate the form fields

      • formname (str) – if given, the form with name attribute set to this value will be used.

      • formid (str) – if given, the form with id attribute set to this value will be used.

      • formxpath (str) – if given, the first form that matches the xpath will be used.

      • formcss (str) – if given, the first form that matches the css selector will be used.

      • formnumber (int) – the number of form to use, when the response contains multiple forms. The first one (and also the default) is 0.

      • formdata (dict) – fields to override in the form data. If a field was already present in the response <form> element, its value is overridden by the one passed in this parameter. If a value passed in this parameter is None, the field will not be included in the request, even if it was present in the response <form> element.

      • clickdata (dict) – attributes to lookup the control clicked. If it’s not given, the form data will be submitted simulating a click on the first clickable element. In addition to html attributes, the control can be identified by its zero-based index relative to other submittable inputs inside the form, via the nr attribute.

      • dont_click (bool) – If True, the form data will be submitted without clicking in any element.

  1. The other parameters of this class method are passed directly to the `FormRequest` `__init__` method.

Request usage examples

Using FormRequest to send data via HTTP POST

If you want to simulate a HTML Form POST in your spider and send a couple of key-value fields, you can return a FormRequest object (from your spider) like this:

  1. return [FormRequest(url="http://www.example.com/post/action",
  2. formdata={'name': 'John Doe', 'age': '27'},
  3. callback=self.after_post)]

Using FormRequest.from_response() 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). When scraping, you’ll want these fields to be automatically pre-populated and only override a couple of them, such as the user name and password. You can use the FormRequest.from_response() method for this job. Here’s an example spider which uses it:

  1. import scrapy
  2. def authentication_failed(response):
  3. # TODO: Check the contents of the response and return True if it failed
  4. # or False if it succeeded.
  5. pass
  6. class LoginSpider(scrapy.Spider):
  7. name = 'example.com'
  8. start_urls = ['http://www.example.com/users/login.php']
  9. def parse(self, response):
  10. return scrapy.FormRequest.from_response(
  11. response,
  12. formdata={'username': 'john', 'password': 'secret'},
  13. callback=self.after_login
  14. )
  15. def after_login(self, response):
  16. if authentication_failed(response):
  17. self.logger.error("Login failed")
  18. return
  19. # continue scraping with authenticated session...

JsonRequest

The JsonRequest class extends the base Request class with functionality for dealing with JSON requests.

class scrapy.http.JsonRequest(url[, … data, dumps_kwargs])[source]

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

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

  • Parameters

    • data (object) – is any JSON serializable object that needs to be JSON encoded and assigned to body. if Request.body argument is provided this parameter will be ignored. if Request.body argument is not provided and data argument is provided Request.method will be set to 'POST' automatically.

    • dumps_kwargs (dict) – Parameters that will be passed to underlying json.dumps() method which is used to serialize data into JSON format.

  • attributes: Tuple[str, …] = (‘url’, ‘callback’, ‘method’, ‘headers’, ‘body’, ‘cookies’, ‘meta’, ‘encoding’, ‘priority’, ‘dont_filter’, ‘errback’, ‘flags’, ‘cb_kwargs’, ‘dumps_kwargs’)

    A tuple of 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(), Request.to_dict() and request_from_dict().

JsonRequest usage example

Sending a JSON POST request with a JSON payload:

  1. data = {
  2. 'name1': 'value1',
  3. 'name2': 'value2',
  4. }
  5. yield JsonRequest(url='http://www.example.com/post/action', data=data)

Response objects

class scrapy.http.Response(\args, **kwargs*)[source]

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

  • Parameters

    • url (str) – the URL of this response

    • status (int) – the HTTP status of the response. Defaults to 200.

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

    • body (bytes) – the response body. To access the decoded text as a string, use response.text from an encoding-aware Response subclass, such as TextResponse.

    • flags (list) – is a list containing the initial values for the Response.flags attribute. If given, the list will be shallow copied.

    • request (scrapy.Request) – the initial value of the Response.request attribute. This represents the Request that generated this response.

    • certificate (twisted.internet.ssl.Certificate) – an object representing the server’s SSL certificate.

    • ip_address (ipaddress.IPv4Address or ipaddress.IPv6Address) – The IP address of the server from which the Response originated.

    • protocol (str) – The protocol that was used to download the response. For instance: “HTTP/1.0”, “HTTP/1.1”, “h2”

New in version 2.0.0: The certificate parameter.

New in version 2.1.0: The ip_address parameter.

New in version 2.5.0: The protocol parameter.

  • url

    A string containing the URL of the response.

    This attribute is read-only. To change the URL of a Response use replace().

  • status

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

  • headers

    A dictionary-like object which contains the response headers. Values can be accessed using get() to return the first 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:

    1. response.headers.getlist('Set-Cookie')
  • body

    The response body as bytes.

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

    This attribute is read-only. To change the body of a Response use replace().

  • request

    The 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. 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 equal Response.url

    • This attribute is only available in the spider code, and in the Spider Middlewares, but not in Downloader Middlewares (although you have the Request available there by other means) and handlers of the response_downloaded signal.

  • meta

    A shortcut to the Request.meta attribute of the Response.request object (i.e. self.request.meta).

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

    See also

    Request.meta attribute

  • cb_kwargs

    New in version 2.0.

    A shortcut to the Request.cb_kwargs attribute of the Response.request object (i.e. self.request.cb_kwargs).

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

    See also

    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

    New in version 2.0.0.

    A twisted.internet.ssl.Certificate object representing the server’s SSL certificate.

    Only populated for https responses, None otherwise.

  • ip_address

    New in version 2.1.0.

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

    This attribute is currently only populated by the HTTP 1.1 download handler, i.e. for http(s) responses. For other handlers, ip_address is always None.

  • protocol

    New in version 2.5.0.

    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 is always None.

  • attributes: Tuple[str, …] = (‘url’, ‘status’, ‘headers’, ‘body’, ‘flags’, ‘request’, ‘certificate’, ‘ip_address’, ‘protocol’)

    A tuple of 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().

  • copy()[source]

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

  • replace([url, status, headers, body, request, flags, cls])[source]

    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 is copied by default.

  • urljoin(url)[source]

    Constructs an absolute url by combining the Response’s url with a possible relative url.

    This is a wrapper over urljoin(), it’s merely an alias for making this call:

    1. urllib.parse.urljoin(response.url, url)
  • follow(url, callback=None, method=’GET’, headers=None, body=None, cookies=None, meta=None, encoding=’utf-8’, priority=0, dont_filter=False, errback=None, cb_kwargs=None, flags=None) → Request[source]

    Return a 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 scrapy.link.Link object, not only an absolute URL.

    TextResponse provides a follow() method which supports selectors in addition to absolute/relative URLs and Link objects.

    New in version 2.0: The flags parameter.

  • follow_all(urls, callback=None, method=’GET’, headers=None, body=None, cookies=None, meta=None, encoding=’utf-8’, priority=0, dont_filter=False, errback=None, cb_kwargs=None, flags=None) → Generator[Request, None, None][source]

    New in version 2.0.

    Return an iterable of 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 objects, not only absolute URLs.

    TextResponse provides a follow_all() method which supports selectors in addition to absolute/relative URLs and Link objects.

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(url[, encoding[, ]])[source]

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

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

  • Parameters

    encoding (str) – is a string which contains the encoding to use for this response. If you create a 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 objects support the following attributes in addition to the standard 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:

    1. >>> str(b'body')
    2. "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 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 HtmlResponse and 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.

  • selector

    A Selector instance using the response as target. The selector is lazily instantiated on first access.

  • attributes: Tuple[str, …] = (‘url’, ‘status’, ‘headers’, ‘body’, ‘flags’, ‘request’, ‘certificate’, ‘ip_address’, ‘protocol’, ‘encoding’)

    A tuple of 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().

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

  • xpath(query)[source]

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

    1. response.xpath('//p')
  • css(query)[source]

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

    1. response.css('p')
  • follow(url, callback=None, method=’GET’, headers=None, body=None, cookies=None, meta=None, encoding=None, priority=0, dont_filter=False, errback=None, cb_kwargs=None, flags=None) → Request[source]

    Return a 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 object, e.g. the result of Link Extractors

    • a Selector object for a <link> or <a> element, e.g. response.css('a.my_link')[0]

    • an attribute Selector (not SelectorList), e.g. response.css('a::attr(href)')[0] or response.xpath('//img/@src')[0]

    See A shortcut for creating Requests for usage examples.

  • follow_all(urls=None, callback=None, method=’GET’, headers=None, body=None, cookies=None, meta=None, encoding=None, priority=0, dont_filter=False, errback=None, cb_kwargs=None, flags=None, css=None, xpath=None) → Generator[Request, None, None][source]

    A generator that produces Request instances to follow all links in urls. It accepts the same arguments as the 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 object, e.g. the result of Link Extractors

    • a Selector object for a <link> or <a> element, e.g. response.css('a.my_link')[0]

    • an attribute 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)

  • json()[source]

    New in version 2.2.

    Deserialize a JSON document to a Python object.

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

  • urljoin(url)[source]

    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 the Response’s url if there is no such tag.

HtmlResponse objects

class scrapy.http.HtmlResponse(url[, ])[source]

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

XmlResponse objects

class scrapy.http.XmlResponse(url[, ])[source]

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