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]
A Request object represents an HTTP request, which is usually generated in the Spider and executed by the Downloader, and thus generating a Response.
Parameters
url (string) –
the URL of this request
If the URL is invalid, a
ValueErrorexception is raised.callback (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 (string) – the HTTP method of this request. Defaults to
'GET'.meta (dict) – the initial values for the
Request.metaattribute. If given, the dict passed in this parameter will be shallow copied.body (str or unicode) – the request body. If a
unicodeis passed, then it’s encoded tostrusing theencodingpassed (which defaults toutf-8). Ifbodyis not given, an empty string is stored. Regardless of the type of this argument, the final value stored will be astr(neverunicodeorNone).headers (dict) – the headers of this request. The dict values can be strings (for single valued headers) or lists (for multi-valued headers). If
Noneis passed as value, the HTTP header will not be sent at all.-
the request cookies. These can be sent in two forms.
Using a dict:
request_with_cookies = Request(url="http://www.example.com",cookies={'currency': 'USD', 'country': 'UY'})
Using a list of dicts:
request_with_cookies = Request(url="http://www.example.com",cookies=[{'name': 'currency','value': 'USD','domain': 'example.com','path': '/currency'}])
The latter form allows for customizing the
domainandpathattributes 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_cookieskey toTrueinrequest.meta.Example of a request that sends manually-defined cookies and ignores cookie storage:
Request(url="http://www.example.com",cookies={'currency': 'USD', 'country': 'UY'},meta={'dont_merge_cookies': True},)
For more info see CookiesMiddleware.
encoding (string) – the encoding of this request (defaults to
'utf-8'). This encoding will be used to percent-encode the URL and to convert the body tostr(if given asunicode).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 (boolean) – 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 (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
Failureas 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.
urlA 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().methodA string representing the HTTP method in the request. This is guaranteed to be uppercase. Example:
"GET","POST","PUT", etcheadersA dictionary-like object which contains the request headers.
bodyA str that contains the request body.
This attribute is read-only. To change the body of a Request use
replace().metaA 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()orreplace()methods, and can also be accessed, in your spider, from theresponse.metaattribute.cb_kwargsA 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
Responseobject as argument.This dict is shallow copied when the request is cloned using the
copy()orreplace()methods, and can also be accessed, in your spider, from theresponse.cb_kwargsattribute.In case of a failure to process the request, this dict can be accessed as
failure.request.cb_kwargsin the request’s errback. For more information, see Accessing additional data in errback functions.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_kwargsandRequest.metaattributes 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, ignore_unknown_options=True, \*kwargs*)[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
Requestclass, 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()fromRequestsubclasses, such asJSONRequest, orXmlRpcRequest, as well as having downloader middlewares and spider middlewares enabled, such asDefaultHeadersMiddleware,UserAgentMiddleware, orHttpCompressionMiddleware, may modify theRequestobject.To translate a cURL command into a Scrapy request, you may use curl2scrapy.
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:
def parse_page1(self, response):return scrapy.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.htmlself.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:
def parse(self, response):request = scrapy.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 callbackyield requestdef parse_page2(self, response, main_url, foo):yield dict(main_url=main_url,other_url=response.url,foo=foo,)
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:
import scrapyfrom scrapy.spidermiddlewares.httperror import HttpErrorfrom twisted.internet.error import DNSLookupErrorfrom twisted.internet.error import TimeoutError, TCPTimedOutErrorclass ErrbackSpider(scrapy.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"http://www.httphttpbinbin.org/", # DNS error expected]def start_requests(self):for u in self.start_urls:yield scrapy.Request(u, callback=self.parse_httpbin,errback=self.errback_httpbin,dont_filter=True)def parse_httpbin(self, response):self.logger.info('Got successful response from {}'.format(response.url))# do something useful here...def errback_httpbin(self, failure):# log all failuresself.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 responseresponse = failure.value.responseself.logger.error('HttpError on %s', response.url)elif failure.check(DNSLookupError):# this is the original requestrequest = failure.requestself.logger.error('DNSLookupError on %s', request.url)elif failure.check(TimeoutError, TCPTimedOutError):request = failure.requestself.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:
def parse(self, response):request = scrapy.Request('http://www.example.com/index.html',callback=self.parse_page2,errback=self.errback_page2,cb_kwargs=dict(main_url=response.url))yield requestdef parse_page2(self, response, main_url):passdef errback_page2(self, failure):yield dict(main_url=failure.request.cb_kwargs['main_url'],)
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:
ftp_user(SeeFTP_USERfor more info)ftp_password(SeeFTP_PASSWORDfor more info)
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 bytes_received signal handler will stop the download of a given response. See the following example:
import scrapyclass StopSpider(scrapy.Spider):name = "stop"start_urls = ["https://docs.scrapy.org/en/latest/"]@classmethoddef from_crawler(cls, crawler):spider = super().from_crawler(crawler)crawler.signals.connect(spider.on_bytes_received, signal=scrapy.signals.bytes_received)return spiderdef parse(self, response):# 'last_chars' show that the full response was not downloadedyield {"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 opened2020-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_received2020-05-19 17:26:13 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://docs.scrapy.org/en/latest/> (referer: None) ['download_stopped']2020-05-19 17:26:13 [scrapy.core.scraper] DEBUG: Scraped from <200 https://docs.scrapy.org/en/latest/>{'len': 279, 'last_chars': 'dth, initial-scale=1.0">\n \n <title>Scr'}2020-05-19 17:26:13 [scrapy.core.engine] INFO: Closing spider (finished)
By default, resulting responses are handled by their corresponding errbacks. To call their callback instead, like in this example, pass fail=False to the StopDownload 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.``FormRequest(url[, formdata, …])[source]
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 iterable of tuples) – 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
from_response(response[, formname=None, formid=None, formnumber=0, formdata=None, formxpath=None, formcss=None, clickdata=None, dont_click=False, …])[source]Returns a new
FormRequestobject 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 defaultfrom_response()behaviour may not be the most appropriate. To disable this behaviour you can set thedont_clickargument toTrue. Also, if you want to change the control clicked (instead of disabling it) you can also use theclickdataargument.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 (
Responseobject) – the response containing a HTML form which will be used to pre-populate the form fieldsformname (string) – if given, the form with name attribute set to this value will be used.
formid (string) – if given, the form with id attribute set to this value will be used.
formxpath (string) – if given, the first form that matches the xpath will be used.
formcss (string) – if given, the first form that matches the css selector will be used.
formnumber (integer) – 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 isNone, 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
nrattribute.dont_click (boolean) – If True, the form data will be submitted without clicking in any element.
The other parameters of this class method are passed directly to the [`FormRequest`](#scrapy.http.FormRequest "scrapy.http.FormRequest") `__init__` method.New in version 0.10.3: The `formname` parameter.New in version 0.17: The `formxpath` parameter.New in version 1.1.0: The `formcss` parameter.New in version 1.1.0: The `formid` parameter.
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:
return [FormRequest(url="http://www.example.com/post/action",formdata={'name': 'John Doe', 'age': '27'},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:
import scrapydef authentication_failed(response):# TODO: Check the contents of the response and return True if it failed# or False if it succeeded.passclass LoginSpider(scrapy.Spider):name = 'example.com'start_urls = ['http://www.example.com/users/login.php']def parse(self, response):return scrapy.FormRequest.from_response(response,formdata={'username': 'john', 'password': 'secret'},callback=self.after_login)def after_login(self, response):if authentication_failed(response):self.logger.error("Login failed")return# 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 (JSON serializable object) – is any JSON serializable object that needs to be JSON encoded and assigned to body. if
Request.bodyargument is provided this parameter will be ignored. ifRequest.bodyargument is not provided and data argument is providedRequest.methodwill 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.
JsonRequest usage example
Sending a JSON POST request with a JSON payload:
data = {'name1': 'value1','name2': 'value2',}yield JsonRequest(url='http://www.example.com/post/action', data=data)
Response objects
class scrapy.http.``Response(\args, **kwargs*)[source]
A Response object represents an HTTP response, which is usually downloaded (by the Downloader) and fed to the Spiders for processing.
Parameters
url (string) – the URL of this response
status (integer) – 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 str you can use
response.textfrom an encoding-aware Response subclass, such asTextResponse.flags (list) – is a list containing the initial values for the
Response.flagsattribute. If given, the list will be shallow copied.request (scrapy.http.Request) – the initial value of the
Response.requestattribute. This represents theRequestthat generated this response.certificate (twisted.internet.ssl.Certificate) – an object representing the server’s SSL certificate.
ip_address (
ipaddress.IPv4Addressoripaddress.IPv6Address) – The IP address of the server from which the Response originated.
New in version 2.1.0: The ip_address parameter.
urlA string containing the URL of the response.
This attribute is read-only. To change the URL of a Response use
replace().statusAn integer representing the HTTP status of the response. Example:
200,404.headersA dictionary-like object which contains the response headers. Values can be accessed using
get()to return the first header value with the specified name orgetlist()to return all header values with the specified name. For example, this call will give you all cookies in the headers:response.headers.getlist('Set-Cookie')
bodyThe body of this Response. Keep in mind that Response.body is always a bytes object. If you want the unicode version use
TextResponse.text(only available inTextResponseand subclasses).This attribute is read-only. To change the body of a Response use
replace().requestThe
Requestobject 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_downloadedsignal.
metaA shortcut to the
Request.metaattribute of theResponse.requestobject (i.e.self.request.meta).Unlike the
Response.requestattribute, theResponse.metaattribute is propagated along redirects and retries, so you will get the originalRequest.metasent from your spider.See also
Request.metaattributecb_kwargsNew in version 2.0.
A shortcut to the
Request.cb_kwargsattribute of theResponse.requestobject (i.e.self.request.cb_kwargs).Unlike the
Response.requestattribute, theResponse.cb_kwargsattribute is propagated along redirects and retries, so you will get the originalRequest.cb_kwargssent from your spider.See also
Request.cb_kwargsattributeflagsA 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.certificateA
twisted.internet.ssl.Certificateobject representing the server’s SSL certificate.Only populated for
httpsresponses,Noneotherwise.ip_addressNew 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_addressis alwaysNone.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.metais copied by default.urljoin(url)[source]Constructs an absolute url by combining the Response’s
urlwith a possible relative url.This is a wrapper over
urljoin(), it’s merely an alias for making this call: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)[source]Return a
Requestinstance to follow a linkurl. It accepts the same arguments asRequest.__init__method, buturlcan be a relative URL or ascrapy.link.Linkobject, not only an absolute URL.TextResponseprovides afollow()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)[source]New in version 2.0.
Return an iterable of
Requestinstances to follow all links inurls. It accepts the same arguments asRequest.__init__method, but elements ofurlscan be relative URLs orLinkobjects, not only absolute URLs.TextResponseprovides afollow_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 (string) – is a string which contains the encoding to use for this response. If you create a
TextResponseobject with a unicode body, it will be encoded using this encoding (remember the body attribute is always a string). IfencodingisNone(default value), 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:
textResponse body, as unicode.
The same as
response.body.decode(response.encoding), but the result is cached after the first call, so you can accessresponse.textmultiple times without extra overhead.Note
unicode(response.body)is not a correct way to convert response body to unicode: you would be using the system default encoding (typicallyascii) instead of the response encoding.encodingA string with the encoding of this response. The encoding is resolved by trying the following mechanisms, in order:
the encoding passed in the
__init__methodencodingargumentthe 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.
the encoding declared in the response body. The TextResponse class doesn’t provide any special functionality for this. However, the
HtmlResponseandXmlResponseclasses do.the encoding inferred by looking at the response body. This is the more fragile method but also the last one tried.
selectorA
Selectorinstance using the response as target. The selector is lazily instantiated on first access.
TextResponse objects support the following methods in addition to the standard Response ones:
xpath(query)[source]A shortcut to
TextResponse.selector.xpath(query):response.xpath('//p')
css(query)[source]A shortcut to
TextResponse.selector.css(query):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)[source]Return a
Requestinstance to follow a linkurl. It accepts the same arguments asRequest.__init__method, buturlcan be not only an absolute URL, but alsoa relative URL
a
Linkobject, e.g. the result of Link Extractorsa
Selectorobject 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]orresponse.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)[source]A generator that produces
Requestinstances to follow all links inurls. It accepts the same arguments as theRequest’s__init__method, except that eachurlselement does not need to be an absolute URL, it can be any of the following:a relative URL
a
Linkobject, e.g. the result of Link Extractorsa
Selectorobject 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]orresponse.xpath('//img/@src')[0]
In addition,
cssandxpatharguments are accepted to perform the link extraction within thefollow_allmethod (only one ofurls,cssandxpathis accepted).Note that when passing a
SelectorListas argument for theurlsparameter or using thecssorxpathparameters, this method will not produce requests for selectors from which links cannot be obtained (for instance, anchor tags without anhrefattribute)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.
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.