Requests and Responses
Scrapy uses Request and Response objects for crawling
websites.
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
Creating requests that submit HTML forms
Use form2request to build request data from an HTML
<form> element and convert it to a Request.
Install it with pip:
pip install form2request
Select the desired form with CSS or XPath, then build and convert request data:
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:
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:
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 DUPEFILTER_CLASS) or caching responses (see
HTTPCACHE_POLICY), where you need the ability to generate a short,
unique identifier from a Request object: a request
fingerprint.
You often do not need to worry about request fingerprints, the default request fingerprinter works for most projects.
However, there is no universal way to generate a unique identifier from a request, because different situations require comparing requests differently. For example, sometimes you may need to compare URLs case-insensitively, include URL fragments, exclude certain URL query parameters, include some or all headers, etc.
To change how request fingerprints are built for your requests, use the
REQUEST_FINGERPRINTER_CLASS setting.
REQUEST_FINGERPRINTER_CLASS
Default: scrapy.utils.request.RequestFingerprinter
A request fingerprinter class or its import path.
Writing your own request fingerprinter
A request fingerprinter is a component that must implement the following method:
- fingerprint(self, request: scrapy.Request)
Return a
bytesobject that uniquely identifies request.See also Request fingerprint restrictions.
The fingerprint() method of the default request fingerprinter,
scrapy.utils.request.RequestFingerprinter, uses
scrapy.utils.request.fingerprint() with its default parameters. For some
common use cases you can use scrapy.utils.request.fingerprint() as well
in your fingerprint() method implementation:
By default, request fingerprinting canonicalizes the request URL. If
verbatim_url is set to True, fingerprinting does not
canonicalize the URL, and the keep_fragments parameter is ignored (it is
effectively true).
For example, to take the value of a request header named X-ID into
account:
# 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"])
To deduplicate repeated query string parameters, such as those some sites
add on every redirect and can otherwise cause redirect loops, build the
deduplicated URL yourself and delegate the rest to
scrapy.utils.request.fingerprint():
# my_project/settings.py
REQUEST_FINGERPRINTER_CLASS = "my_project.utils.RequestFingerprinter"
# my_project/utils.py
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
from weakref import WeakKeyDictionary
from scrapy.utils.request import fingerprint
class RequestFingerprinter:
cache = WeakKeyDictionary()
def fingerprint(self, request):
if request not in self.cache:
parts = urlsplit(request.url)
query = urlencode(list(set(parse_qsl(parts.query))))
deduped_url = urlunsplit(parts._replace(query=query))
deduped_request = request.replace(url=deduped_url)
self.cache[request] = fingerprint(deduped_request)
return self.cache[request]
You can also write your own fingerprinting logic from scratch.
However, if you do not use scrapy.utils.request.fingerprint(), make sure
you use WeakKeyDictionary to cache request fingerprints:
Caching saves CPU by ensuring that fingerprints are calculated only once per request, and not once per Scrapy component that needs the fingerprint of a request.
Using
WeakKeyDictionarysaves memory by ensuring that request objects do not stay in memory forever just because you have references to them in your cache dictionary.
For example, to take into account only the URL of a request, without any prior URL canonicalization or taking the request method or body into account:
from hashlib import sha1
from weakref import WeakKeyDictionary
class RequestFingerprinter:
cache = WeakKeyDictionary()
def fingerprint(self, request):
if request not in self.cache:
fp = sha1()
fp.update(request.url.encode())
self.cache[request] = fp.digest()
return self.cache[request]
If you need to be able to override the request fingerprinting for arbitrary
requests from your spider callbacks, you may implement a request fingerprinter
that reads fingerprints from request.meta
when available, and then falls back to
scrapy.utils.request.fingerprint(). For example:
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:
from hashlib import sha1
from weakref import WeakKeyDictionary
from w3lib.url import canonicalize_url
class RequestFingerprinter:
cache = WeakKeyDictionary()
def fingerprint(self, request):
if request not in self.cache:
fp = sha1()
fp.update(request.method.encode())
fp.update(canonicalize_url(request.url).encode())
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 request fingerprinter generates.
The following built-in Scrapy components have such restrictions:
scrapy.extensions.httpcache.FilesystemCacheStorage(default value ofHTTPCACHE_STORAGE)Request fingerprints must be at least 1 byte long.
Path and filename length limits of the file system of
HTTPCACHE_DIRalso apply. InsideHTTPCACHE_DIR, the following directory structure is created:the partition that
HTTPCACHE_SCOPEselects, i.e.Spider.nameor the request host, and no folder at all with'none'first byte of a request fingerprint as hexadecimal
fingerprint as hexadecimal
filenames up to 16 characters long
For example, if a request fingerprint is made of 20 bytes (default),
HTTPCACHE_DIRis'/home/user/project/.scrapy/httpcache', and the name of your spider is'my_spider'your file system must support a file path like:/home/user/project/.scrapy/httpcache/my_spider/01/0123456789abcdef0123456789abcdef01234567/response_headers
scrapy.extensions.httpcache.DbmCacheStorageThe 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 Response of a
Request once that request has been downloaded, so that you can
extract data from that response and generate additional requests to continue
the crawl:
from scrapy import Request, Spider
class BookSpider(Spider):
name = "books"
async def start(self):
yield Request("https://books.toscrape.com/", callback=self.parse_home)
def parse_home(self, response):
for url in response.css("h3 a::attr(href)").getall():
yield Request(response.urljoin(url), callback=self.parse_book)
def parse_book(self, response):
yield {"title": response.css("h1::text").get()}
Requests may also define an errback, 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.
Assigning a callback to a request
To assign a callback to a request, use the callback parameter of
Request, which sets the Request.callback attribute:
from scrapy import Request
def parse_home(response): ...
request = Request("https://books.toscrape.com/", callback=parse_home)
Requests with no callback, i.e. with callback set to
None, are handled by the parse() method of the spider:
request = Request("https://books.toscrape.com/") # Handled by parse()
If a request is never meant to reach a spider callback, e.g. because a
component sends it and handles its response itself,
assign the special NO_CALLBACK() value to it
instead, so that downloader middlewares
can tell such requests apart.
While callback only accepts callables, some spider
classes let you also define a callback by name: both CrawlSpider.rules and SitemapSpider.sitemap_rules accept the name of a spider
method as a string.
Writing a callback
Any callable can be a callback, as long as it takes the response as its first positional parameter, and any additional callback data as keyword parameters. Spider methods are the most common choice, but plain functions, lambda expressions and other callable objects work as well.
Note
If you enable job persistence through the
JOBDIR setting, callbacks must be methods of the running spider.
Requests with any other callback cannot be serialized, so they are kept in
memory only and lost when you pause the crawl. See
Request serialization.
A callback can be:
A regular function:
def parse(self, response): return {"url": response.url}
A generator function:
def parse(self, response): yield {"url": response.url}
A coroutine function, i.e. defined with
async def:async def parse(self, response): return {"url": response.url}
An asynchronous generator function:
async def parse(self, response): yield {"url": response.url}
The last two allow using await, async for and async with in your
callback. See Coroutines.
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.
Nonevalues within an iterable of callback output are ignored as well.A
Requestobject, which Scrapy schedules, downloads and eventually sends to its own callback.An item object, which Scrapy sends to the item pipelines.
Any object that is neither
Nonenor aRequestobject is treated as an item.An iterable of any of the values above, e.g. a list or, more commonly, a generator.
Asynchronous iterables, e.g. an asynchronous generator, are also supported.
Note
When a callback returns an object, Scrapy iterates that object if
it supports iteration, except for dict, Item,
str and bytes objects, which are always handled as single
items.
Note
In a generator callback, a return statement with a value does not
produce any output, since such a value is not part of what the generator
yields. Scrapy logs a warning when it detects such a callback, see
WARN_ON_GENERATOR_RETURN_VALUE.
Before Scrapy acts on the output of a callback, that output goes through the
process_spider_output() method
of your spider middlewares, which may modify
it or drop part of it.
If a callback raises an exception, the errback of the
request is not called. The exception goes through the
process_spider_exception()
method of your spider middlewares instead and, unless one of them handles it,
Scrapy logs it and sends the spider_error 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
Request.cb_kwargs attribute:
from scrapy import Request
def parse(self, response):
request = Request(
"http://www.example.com/index.html",
callback=self.parse_page2,
cb_kwargs=dict(main_url=response.url),
)
request.cb_kwargs["foo"] = "bar" # add more arguments for the callback
yield request
def parse_page2(self, response, main_url, foo):
yield dict(
main_url=main_url,
other_url=response.url,
foo=foo,
)
Request.cb_kwargs is the recommended way to pass your own data to a
callback. Use Request.meta only for data aimed at components, such as middlewares and extensions.
Errbacks
The errback of a request is a function that will be called when an exception is raised while processing it.
It receives a Failure as first parameter and can
be used to track connection establishment timeouts, DNS errors etc.
Scrapy sets the request attribute of that
Failure object to the Request
object being processed.
If an errback raises an exception, Scrapy logs it and sends the
spider_error signal, unless the exception is the one that the errback
received, which Scrapy logs as a download error instead.
Here’s an example spider logging all errors and catching some specific errors if needed:
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:
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 Request.meta attribute can contain any arbitrary data, but there
are some special keys recognized by Scrapy and its built-in extensions.
Those are:
allow_offsiteis_start_requestrule
Scrapy components also use meta keys whose name starts with an underscore, such
as _auth_proxy. Those are internal, and may change or disappear at any time.
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, ora
(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:
Request(
"https://example.org",
meta={"bindaddress": "127.0.0.2"},
)
Request(
"https://example.org",
meta={"bindaddress": ("127.0.0.2", 50000)},
)
If not set, built-in HTTP download handlers use the value of
DOWNLOAD_BIND_ADDRESS as the default bind address.
Set the bindaddress request meta key to override it for a
specific request.
This meta key is not supported by
HttpxDownloadHandler and
AiohttpDownloadHandler, but
the DOWNLOAD_BIND_ADDRESS setting is supported by them.
body_file
Added in version 2.20.0.
Path of a file where the response body is written as it is downloaded, or
True to write it to a new temporary file, so that responses of any size can
be downloaded without fitting them in memory:
Request("https://example.com/big.zip", meta={"body_file": "big.zip"})
The response is then a BodyFileResponse.
Each download attempt, e.g. a retry or a redirect, writes the file from the
start. If the download fails, e.g. because the response exceeds
DOWNLOAD_MAXSIZE, the file may hold part of the body, except for
temporary files, which Scrapy deletes. Deleting temporary files of successful
downloads is up to you.
Scrapy does not ask for a compressed response, and does not decompress the file
if the server sends one anyway, as indicated by the Content-Encoding
response header.
HttpCacheMiddleware skips
these requests.
Download handlers that do not support this key, such as some built-in
ones, make the request fail with
NotSupported.
delay
Added in version 2.20.0.
Number of seconds to hold a request before sending it:
Request("https://example.com/slow", meta={"delay": 5.0})
The delay is a minimum: once it elapses, the request competes with the other
pending requests as usual, subject to e.g. its
priority, CONCURRENT_REQUESTS_PER_DOMAIN and
DOWNLOAD_DELAY.
Scrapy removes this key as soon as the countdown starts, so that a copy of the
request, e.g. a retry or a redirect, is not held again, and so that setting the
key again asks for a new delay. See also delayed.
delayed
Added in version 2.20.0.
Delays, in seconds, that a request has been held for because of
delay. Read-only.
def parse(self, response):
delays = response.meta.get("delayed", [])
self.logger.info(f"Held {len(delays)} times, {sum(delays)}s in total")
download_handler
Added in version 2.20.0.
ID of the download handler to use for this
request, either a name from DOWNLOAD_HANDLERS_BY_NAME or a URL
scheme from DOWNLOAD_HANDLERS. See Choosing a download handler per 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. It covers the time until Scrapy reads the response, which your own code can delay, see Keeping the event loop free. 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.
ftp_local_filename
Path, as bytes, of the file where to write the response body of an
ftp:// request. If set, Response.body
holds this path instead of the file contents.
give_up_log_level
Added in version 2.17.0.
Logging level used for the message logged when a request
exceeds its retries. See RETRY_GIVE_UP_LOG_LEVEL for details.
http_auth_domain
Added in version 2.17.0.
Overrides HTTPAUTH_DOMAIN for this request.
If this key is not set, http_user and http_pass are only
sent to the origin (scheme, host and port) of the request where they were first
used, e.g. they are not sent after a cross-origin redirect.
http_pass
Added in version 2.17.0.
Overrides HTTPAUTH_PASS for this request.
http_user
Added in version 2.17.0.
Overrides HTTPAUTH_USER for this request.
is_robotstxt_request
Added in version 2.20.0.
True on the robots.txt requests that
RobotsTxtMiddleware sends, so
that downloader middlewares can tell them
apart from other requests.
max_retry_times
The meta key is used set retry times per request. When set, the
max_retry_times meta key takes higher precedence over the
RETRY_TIMES setting.
proxy_headers
Added in version 2.20.0.
Headers for the proxy set in the proxy metadata key, as a mapping,
e.g. {"X-Proxy-Country": "us"}.
Request(
"https://example.com",
meta={
"proxy": "http://proxy.example:8080",
"proxy_headers": {"X-Proxy-Country": "us"},
},
)
For HTTPS URLs these headers are sent in the CONNECT request that opens the
tunnel through the proxy, which the target server cannot see. For other URLs
there is no tunnel, so they are sent among the request headers, and it is up to
the proxy to consume them instead of passing them on to the target server.
Note
Handling of this metadata key needs to be implemented inside the
download handler, so it’s not guaranteed
to be supported by all 3rd-party handlers. Among the built-in handlers,
HTTP11DownloadHandler,
HttpxDownloadHandler and
AiohttpDownloadHandler
support it for HTTP and HTTPS proxies.
skip_dupefilter_once
Added in version 2.20.0.
Set this key to True to skip duplicate filtering for this request. The scheduler
removes this key, so requests derived from this request, e.g. redirects, are
filtered as usual.
get_retry_request() sets this key.
verbatim_url
Added in version 2.17.0.
Set this key to True to keep the request URL as passed to
Request, without URL percent-encoding.
When this key is enabled, fingerprint() does not
canonicalize the request URL, so requests whose URLs differ only in
characters that would otherwise be canonicalized get different fingerprints.
In this mode, the keep_fragments parameter is ignored, and it is
effectively true.
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:
import scrapy
class StopSpider(scrapy.Spider):
name = "stop"
start_urls = ["https://docs.scrapy.org/en/latest/"]
@classmethod
def from_crawler(cls, crawler):
spider = super().from_crawler(crawler)
crawler.signals.connect(
spider.on_bytes_received, signal=scrapy.signals.bytes_received
)
return spider
def parse(self, response):
# 'last_chars' show that the full response was not downloaded
yield {"len": len(response.text), "last_chars": response.text[-40:]}
def on_bytes_received(self, data, request, spider):
raise scrapy.exceptions.StopDownload(fail=False)
which produces the following output:
2020-05-19 17:26:12 [scrapy.core.engine] INFO: Spider opened
2020-05-19 17:26:12 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2020-05-19 17:26:13 [scrapy.core.downloader.handlers.http11] DEBUG: Download stopped for <GET https://docs.scrapy.org/en/latest/> from signal handler StopSpider.on_bytes_received
2020-05-19 17:26:13 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://docs.scrapy.org/en/latest/> (referer: None) ['download_stopped']
2020-05-19 17:26:13 [scrapy.core.scraper] DEBUG: Scraped from <200 https://docs.scrapy.org/en/latest/>
{'len': 279, 'last_chars': 'dth, initial-scale=1.0">\n \n <title>Scr'}
2020-05-19 17:26:13 [scrapy.core.engine] INFO: Closing spider (finished)
By default, resulting responses are handled by their corresponding errbacks. To
call their callback instead, like in this example, pass fail=False to the
StopDownload exception.
Request subclasses
Here is the list of built-in Request subclasses. You can also subclass
it to implement your own custom functionality.
FormRequest
JsonRequest
The JsonRequest class extends the base Request class with functionality for
dealing with JSON requests.
- class scrapy.http.JsonRequest(url[, ... data, dumps_kwargs])
The
JsonRequestclass adds two new keyword parameters to the__init__()method. The remaining arguments are the same as for theRequestclass and are not documented here.Using the
JsonRequestwill set theContent-Typeheader toapplication/jsonandAcceptheader toapplication/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 the
bodyargument is provided this parameter will be ignored. If thebodyargument is not provided and thedataargument is provided themethodwill 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
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[, ...]])
TextResponseobjects adds encoding capabilities to the baseResponseclass, which is meant to be used only for binary data, such as images, sounds or any media file.TextResponseobjects support a new__init__()method argument, in addition to the baseResponseobjects. The remaining functionality is the same as for theResponseclass and is not documented here.- Parameters:
encoding (str) – is a string which contains the encoding to use for this response, as a label of the Encoding Standard, which web browsers implement, or as the name of the Python codec of one of its encodings, e.g.
cp932for Shift_JIS. If you create aTextResponseobject with a string as body, it will be converted to bytes encoded using this encoding. If encoding isNone(default), the encoding will be looked up in the response headers and body instead.
TextResponseobjects support the following attributes in addition to the standardResponseones:- text
Response body, as a string.
The result is cached after the first call, so you can access
response.textmultiple times without extra overhead.Note
str(response.body)is not a correct way to convert the response body into a string:>>> str(b"body") "b'body'"
- encoding
A string with the encoding of this response. The encoding is resolved by trying the following mechanisms, in order:
the encoding passed in the
__init__()methodencodingargumentthe encoding of the byte order mark at the start of the response body
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.
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.
This order matches the encoding sniffing algorithm of the HTML standard, which web browsers follow.
To resolve the encoding differently, determine it yourself and pass it through
Response.replace()from a downloader middleware. Give that middleware an order between those ofMetaRefreshMiddleware(580) andHttpCompressionMiddleware(590), so that it gets a decompressed body and no other component reads the response text before it.For example, to give a declaration in the response body precedence over the Content-Type header:
from w3lib.encoding import html_body_declared_encoding, read_bom from scrapy.http import TextResponse class BodyEncodingMiddleware: def process_response(self, request, response, spider): if not isinstance(response, TextResponse): return response if read_bom(response.body)[0]: return response encoding = html_body_declared_encoding(response.body) return response.replace(encoding=encoding) if encoding else response
- selector
A
Selectorinstance using the response as target. The selector is lazily instantiated on first access.
TextResponseobjects support the following methods in addition to the standardResponseones:- jmespath(query)
A shortcut to
TextResponse.selector.jmespath(query):response.jmespath("object.[*]")
- xpath(query)
A shortcut to
TextResponse.selector.xpath(query):response.xpath("//p")
- css(query)
A shortcut to
TextResponse.selector.css(query):response.css("p")
- urljoin(url)
Constructs an absolute url by combining
base_urlwith a possible relative url.
HtmlResponse objects
- class scrapy.http.HtmlResponse(url[, ...])
The
HtmlResponseclass is a subclass ofTextResponsewhich adds encoding auto-discovering support by looking into the HTML meta http-equiv attribute. SeeTextResponse.encoding.
XmlResponse objects
- class scrapy.http.XmlResponse(url[, ...])
The
XmlResponseclass is a subclass ofTextResponsewhich adds encoding auto-discovering support by looking into the XML declaration line. SeeTextResponse.encoding.
JsonResponse objects
- class scrapy.http.JsonResponse(url[, ...])
The
JsonResponseclass is a subclass ofTextResponsethat is used when the response has a JSON MIME type in its Content-Type header.