Python Scrapy
Python Scrapy
Release 1.0.7
Scrapy developers
1 Getting help 3
2 First steps 5
2.1 Scrapy at a glance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.2 Installation guide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.3 Scrapy Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.4 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
3 Basic concepts 21
3.1 Command line tool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.2 Spiders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3.3 Selectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
3.4 Items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
3.5 Item Loaders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
3.6 Scrapy shell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
3.7 Item Pipeline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
3.8 Feed exports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
3.9 Requests and Responses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
3.10 Link Extractors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
3.11 Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
3.12 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
i
5.8 Debugging memory leaks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
5.9 Downloading and processing files and images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
5.10 Ubuntu packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
5.11 Deploying Spiders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
5.12 AutoThrottle extension . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
5.13 Benchmarking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
5.14 Jobs: pausing and resuming crawls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
ii
Scrapy Documentation, Release 1.0.7
First steps 1
Scrapy Documentation, Release 1.0.7
2 First steps
CHAPTER 1
Getting help
3
Scrapy Documentation, Release 1.0.7
First steps
Scrapy at a glance
Scrapy is an application framework for crawling web sites and extracting structured data which can be used for a wide
range of useful applications, like data mining, information processing or historical archival.
Even though Scrapy was originally designed for web scraping, it can also be used to extract data using APIs (such as
Amazon Associates Web Services) or as a general purpose web crawler.
In order to show you what Scrapy brings to the table, we’ll walk you through an example of a Scrapy Spider using the
simplest way to run a spider.
So, here’s the code for a spider that follows the links to the top voted questions on StackOverflow and scrapes some
data from each page:
import scrapy
class StackOverflowSpider(scrapy.Spider):
name = 'stackoverflow'
start_urls = ['http://stackoverflow.com/questions?sort=votes']
5
Scrapy Documentation, Release 1.0.7
Put this in a file, name it to something like stackoverflow_spider.py and run the spider using the
runspider command:
When this finishes you will have in the top-stackoverflow-questions.json file a list of the most upvoted
questions in StackOverflow in JSON format, containing the title, link, number of upvotes, a list of the tags and the
question content in HTML, looking like this (reformatted for easier reading):
[{
"body": "... LONG HTML HERE ...",
"link": "http://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-
˓→array-faster-than-an-unsorted-array",
When you ran the command scrapy runspider somefile.py, Scrapy looked for a Spider definition inside it
and ran it through its crawler engine.
The crawl started by making requests to the URLs defined in the start_urls attribute (in this case, only the URL
for StackOverflow top questions page) and called the default callback method parse, passing the response object as
an argument. In the parse callback we extract the links to the question pages using a CSS Selector with a custom
extension that allows to get the value for an attribute. Then we yield a few more requests to be sent, registering the
method parse_question as the callback to be called for each of them as they finish.
Here you notice one of the main advantages about Scrapy: requests are scheduled and processed asynchronously. This
means that Scrapy doesn’t need to wait for a request to be finished and processed, it can send another request or do
other things in the meantime. This also means that other requests can keep going even if some request fails or an error
happens while handling it.
While this enables you to do very fast crawls (sending multiple concurrent requests at the same time, in a fault-tolerant
way) Scrapy also gives you control over the politeness of the crawl through a few settings. You can do things like
setting a download delay between each request, limiting amount of concurrent requests per domain or per IP, and even
using an auto-throttling extension that tries to figure out these automatically.
Finally, the parse_question callback scrapes the question data for each page yielding a dict, which Scrapy then
collects and writes to a JSON file as requested in the command line.
Note: This is using feed exports to generate the JSON file, you can easily change the export format (XML or CSV,
for example) or the storage backend (FTP or Amazon S3, for example). You can also write an item pipeline to store
the items in a database.
What else?
You’ve seen how to extract and store items from a website using Scrapy, but this is just the surface. Scrapy provides a
lot of powerful features for making scraping easy and efficient, such as:
• Built-in support for selecting and extracting data from HTML/XML sources using extended CSS selectors and
XPath expressions, with helper methods to extract using regular expressions.
• An interactive shell console (IPython aware) for trying out the CSS and XPath expressions to scrape data, very
useful when writing or debugging your spiders.
• Built-in support for generating feed exports in multiple formats (JSON, CSV, XML) and storing them in multiple
backends (FTP, S3, local filesystem)
• Robust encoding support and auto-detection, for dealing with foreign, non-standard and broken encoding dec-
larations.
• Strong extensibility support, allowing you to plug in your own functionality using signals and a well-defined
API (middlewares, extensions, and pipelines).
• Wide range of built-in extensions and middlewares for handling:
– cookies and session handling
– HTTP features like compression, authentication, caching
– user-agent spoofing
– robots.txt
– crawl depth restriction
– and more
• A Telnet console for hooking into a Python console running inside your Scrapy process, to introspect and debug
your crawler
• Plus other goodies like reusable spiders to crawl sites from Sitemaps and XML/CSV feeds, a media pipeline
for automatically downloading images (or any other media) associated with the scraped items, a caching DNS
resolver, and much more!
What’s next?
The next steps for you are to install Scrapy, follow through the tutorial to learn how to organize your code in Scrapy
projects and join the community. Thanks for your interest!
Installation guide
Installing Scrapy
The installation steps assume that you have the following things installed:
• Python 2.7
• pip and setuptools Python packages. Nowadays pip requires and installs setuptools if not installed. Python 2.7.9
and later include pip by default, so you may have it already.
• lxml. Most Linux distributions ships prepackaged versions of lxml. Otherwise refer to http://lxml.de/
installation.html
• OpenSSL. This comes preinstalled in all operating systems, except Windows where the Python installer ships it
bundled.
You can install Scrapy using pip (which is the canonical way to install Python packages). To install using pip run:
Anaconda
Note: For Windows users, or if you have issues installing through pip, this is the recommended way to install Scrapy.
If you already have installed Anaconda or Miniconda, the company Scrapinghub maintains official conda packages
for Linux, Windows and OS X.
To install Scrapy using conda, run:
Windows
C:\Python27\;C:\Python27\Scripts\;
c:\python27\python.exe c:\python27\tools\scripts\win_add2path.py
Close the command prompt window and reopen it so changes take effect, run the following command and check
it shows the expected Python version:
python --version
pip --version
• At this point Python 2.7 and pip package manager must be working, let’s install Scrapy:
Don’t use the python-scrapy package provided by Ubuntu, they are typically too old and slow to catch up with
latest Scrapy.
Instead, use the official Ubuntu Packages, which already solve all dependencies for you and are continuously updated
with the latest bug fixes.
If you prefer to build the python dependencies locally instead of relying on system packages you’ll need to install their
required non-python dependencies first:
Note: The same non-python dependencies can be used to install Scrapy in Debian Wheezy (7.0) and above.
Archlinux
You can follow the generic instructions or install Scrapy from AUR Scrapy package:
yaourt -S scrapy
Mac OS X
Building Scrapy’s dependencies requires the presence of a C compiler and development headers. On OS X this is
typically provided by Apple’s Xcode development tools. To install the Xcode command line tools open a terminal
window and run:
xcode-select --install
There’s a known issue that prevents pip from updating system packages. This has to be addressed to successfully
install Scrapy and its dependencies. Here are some proposed solutions:
• (Recommended) Don’t use system python, install a new, updated version that doesn’t conflict with the rest of
your system. Here’s how to do it using the homebrew package manager:
– Install homebrew following the instructions in http://brew.sh/
– Update your PATH variable to state that homebrew packages should be used before system packages
(Change .bashrc to .zshrc accordantly if you’re using zsh as default shell):
source ~/.bashrc
– Install python:
– Latest versions of python have pip bundled with them so you won’t need to install it separately. If this is
not the case, upgrade python:
Scrapy Tutorial
In this tutorial, we’ll assume that Scrapy is already installed on your system. If that’s not the case, see Installation
guide.
We are going to use Open directory project (dmoz) as our example domain to scrape.
This tutorial will walk you through these tasks:
1. Creating a new Scrapy project
2. Defining the Items you will extract
3. Writing a spider to crawl a site and extract Items
4. Writing an Item Pipeline to store the extracted Items
Scrapy is written in Python. If you’re new to the language you might want to start by getting an idea of what the
language is like, to get the most out of Scrapy. If you’re already familiar with other languages, and want to learn
Python quickly, we recommend Learn Python The Hard Way. If you’re new to programming and want to start with
Python, take a look at this list of Python resources for non-programmers.
Creating a project
Before you start scraping, you will have to set up a new Scrapy project. Enter a directory where you’d like to store
your code and run:
tutorial/
scrapy.cfg # deploy configuration file
tutorial/ # project's Python module, you'll import your code from here
__init__.py
Items are containers that will be loaded with the scraped data; they work like simple Python dicts. While you can use
plain Python dicts with Scrapy, Items provide additional protection against populating undeclared fields, preventing
typos. They can also be used with Item Loaders, a mechanism with helpers to conveniently populate Items.
They are declared by creating a scrapy.Item class and defining its attributes as scrapy.Field objects, much
like in an ORM (don’t worry if you’re not familiar with ORMs, you will see that this is an easy task).
We begin by modeling the item that we will use to hold the site’s data obtained from dmoz.org. As we want to capture
the name, url and description of the sites, we define fields for each of these three attributes. To do that, we edit
items.py, found in the tutorial directory. Our Item class looks like this:
import scrapy
class DmozItem(scrapy.Item):
title = scrapy.Field()
link = scrapy.Field()
desc = scrapy.Field()
This may seem complicated at first, but defining an item class allows you to use other handy components and helpers
within Scrapy.
Spiders are classes that you define and Scrapy uses to scrape information from a domain (or group of domains).
They define an initial list of URLs to download, how to follow links, and how to parse the contents of pages to extract
items.
To create a Spider, you must subclass scrapy.Spider and define some attributes:
• name: identifies the Spider. It must be unique, that is, you can’t set the same name for different Spiders.
• start_urls: a list of URLs where the Spider will begin to crawl from. The first pages downloaded will be
those listed here. The subsequent URLs will be generated successively from data contained in the start URLs.
• parse(): a method of the spider, which will be called with the downloaded Response object of each start
URL. The response is passed to the method as the first and only argument.
This method is responsible for parsing the response data and extracting scraped data (as scraped items) and more
URLs to follow.
The parse() method is in charge of processing the response and returning scraped data (as Item objects) and
more URLs to follow (as Request objects).
This is the code for our first Spider; save it in a file named dmoz_spider.py under the tutorial/spiders
directory:
import scrapy
class DmozSpider(scrapy.Spider):
name = "dmoz"
allowed_domains = ["dmoz.org"]
start_urls = [
"http://www.dmoz.org/Computers/Programming/Languages/Python/Books/",
"http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/"
]
Crawling
To put our spider to work, go to the project’s top level directory and run:
This command runs the spider with name dmoz that we’ve just added, that will send some requests for the dmoz.org
domain. You will get an output similar to this:
Note: At the end you can see a log line for each URL defined in start_urls. Because these URLs are the starting
ones, they have no referrers, which is shown at the end of the log line, where it says (referer: None).
Now, check the files in the current directory. You should notice two new files have been created: Books.html and
Resources.html, with the content for the respective URLs, as our parse method instructs.
Scrapy creates scrapy.Request objects for each URL in the start_urls attribute of the Spider, and assigns
them the parse method of the spider as their callback function.
These Requests are scheduled, then executed, and scrapy.http.Response objects are returned and then fed
back to the spider, through the parse() method.
Extracting Items
Introduction to Selectors
There are several ways to extract data from web pages. Scrapy uses a mechanism based on XPath or CSS expressions
called Scrapy Selectors. For more information about selectors and other extraction mechanisms see the Selectors
documentation.
Here are some examples of XPath expressions and their meanings:
• /html/head/title: selects the <title> element, inside the <head> element of an HTML document
• /html/head/title/text(): selects the text inside the aforementioned <title> element.
• //td: selects all the <td> elements
• //div[@class="mine"]: selects all div elements which contain an attribute class="mine"
These are just a couple of simple examples of what you can do with XPath, but XPath expressions are indeed much
more powerful. To learn more about XPath, we recommend this tutorial to learn XPath through examples, and this
tutorial to learn “how to think in XPath”.
Note: CSS vs XPath: you can go a long way extracting data from web pages using only CSS selectors. However,
XPath offers more power because besides navigating the structure, it can also look at the content: you’re able to select
things like: the link that contains the text ‘Next Page’. Because of this, we encourage you to learn about XPath even if
you already know how to construct CSS selectors.
For working with CSS and XPath expressions, Scrapy provides Selector class and convenient shortcuts to avoid
instantiating selectors yourself every time you need to select something from a response.
You can see selectors as objects that represent nodes in the document structure. So, the first instantiated selectors are
associated with the root node, or the entire document.
Selectors have four basic methods (click on the method to see the complete API documentation):
• xpath(): returns a list of selectors, each of which represents the nodes selected by the xpath expression given
as argument.
• css(): returns a list of selectors, each of which represents the nodes selected by the CSS expression given as
argument.
• extract(): returns a unicode string with the selected data.
• re(): returns a list of unicode strings extracted by applying the regular expression given as argument.
To illustrate the use of Selectors we’re going to use the built-in Scrapy shell, which also requires IPython (an extended
Python console) installed on your system.
To start a shell, you must go to the project’s top level directory and run:
Note: Remember to always enclose urls in quotes when running Scrapy shell from command-line, otherwise urls
containing arguments (ie. & character) will not work.
In [1]:
After the shell loads, you will have the response fetched in a local response variable, so if you type response.
body you will see the body of the response, or you can type response.headers to see its headers.
More importantly response has a selector attribute which is an instance of Selector class, instantiated with
this particular response. You can run queries on response by calling response.selector.xpath()
or response.selector.css(). There are also some convenience shortcuts like response.xpath() or
response.css() which map directly to response.selector.xpath() and response.selector.
css().
So let’s try it:
In [1]: response.xpath('//title')
Out[1]: [<Selector xpath='//title' data=u'<title>Open Directory - Computers: Progr'>]
In [2]: response.xpath('//title').extract()
Out[2]: [u'<title>Open Directory - Computers: Programming: Languages: Python: Books</
˓→title>']
In [3]: response.xpath('//title/text()')
Out[3]: [<Selector xpath='//title/text()' data=u'Open Directory - Computers:
˓→Programming:'>]
In [4]: response.xpath('//title/text()').extract()
Out[4]: [u'Open Directory - Computers: Programming: Languages: Python: Books']
In [5]: response.xpath('//title/text()').re('(\w+):')
Out[5]: [u'Computers', u'Programming', u'Languages', u'Python']
Now, let’s try to extract some real information from those pages.
You could type response.body in the console, and inspect the source code to figure out the XPaths you need to
use. However, inspecting the raw HTML code there could become a very tedious task. To make it easier, you can
use Firefox Developer Tools or some Firefox extensions like Firebug. For more information see Using Firebug for
scraping and Using Firefox for scraping.
After inspecting the page source, you’ll find that the web site’s information is inside a <ul> element, in fact the
second <ul> element.
So we can select each <li> element belonging to the site’s list with this code:
response.xpath('//ul/li')
response.xpath('//ul/li/text()').extract()
response.xpath('//ul/li/a/text()').extract()
response.xpath('//ul/li/a/@href').extract()
As we’ve said before, each .xpath() call returns a list of selectors, so we can concatenate further .xpath() calls
to dig deeper into a node. We are going to use that property here, so:
Note: For a more detailed description of using nested selectors, see Nesting selectors and Working with relative
XPaths in the Selectors documentation
import scrapy
class DmozSpider(scrapy.Spider):
name = "dmoz"
allowed_domains = ["dmoz.org"]
start_urls = [
"http://www.dmoz.org/Computers/Programming/Languages/Python/Books/",
"http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/"
]
desc = sel.xpath('text()').extract()
print title, link, desc
Now try crawling dmoz.org again and you’ll see sites being printed in your output. Run:
scrapy crawl dmoz
Item objects are custom Python dicts; you can access the values of their fields (attributes of the class we defined
earlier) using the standard dict syntax like:
>>> item = DmozItem()
>>> item['title'] = 'Example title'
>>> item['title']
'Example title'
So, in order to return the data we’ve scraped so far, the final code for our Spider would be like this:
import scrapy
class DmozSpider(scrapy.Spider):
name = "dmoz"
allowed_domains = ["dmoz.org"]
start_urls = [
"http://www.dmoz.org/Computers/Programming/Languages/Python/Books/",
"http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/"
]
Note: You can find a fully-functional variant of this spider in the dirbot project available at https://github.com/scrapy/
dirbot
{'desc': [u' - By David Mertz; Addison Wesley. Book in progress, full text,
˓→ASCII format. Asks for feedback. [author website, Gnosis Software, Inc.\n],
'link': [u'http://gnosis.cx/TPiP/'],
'title': [u'Text Processing in Python']}
[scrapy] DEBUG: Scraped from <200 http://www.dmoz.org/Computers/Programming/Languages/
˓→Python/Books/>
{'desc': [u' - By Sean McGrath; Prentice Hall PTR, 2000, ISBN 0130211192, has CD-
˓→ROM. Methods to build XML applications fast, Python tutorial, DOM and SAX, new
'link': [u'http://www.informit.com/store/product.aspx?isbn=0130211192'],
'title': [u'XML Processing with Python']}
Following links
Let’s say, instead of just scraping the stuff in Books and Resources pages, you want everything that is under the Python
directory.
Now that you know how to extract data from a page, why not extract the links for the pages you are interested, follow
them and then extract the data you want for all of them?
Here is a modification to our spider that does just that:
import scrapy
class DmozSpider(scrapy.Spider):
name = "dmoz"
allowed_domains = ["dmoz.org"]
start_urls = [
"http://www.dmoz.org/Computers/Programming/Languages/Python/",
]
Now the parse() method only extract the interesting links from the page, builds a full absolute URL using the re-
sponse.urljoin method (since the links can be relative) and yields new requests to be sent later, registering as callback
the method parse_dir_contents() that will ultimately scrape the data we want.
What you see here is the Scrapy’s mechanism of following links: when you yield a Request in a callback method,
Scrapy will schedule that request to be sent and register a callback method to be executed when that request finishes.
Using this, you can build complex crawlers that follow links according to rules you define, and extract different kinds
of data depending on the page it’s visiting.
A common pattern is a callback method that extracts some items, looks for a link to follow to the next page and then
yields a Request with the same callback for it:
yield item
This creates a sort of loop, following all the links to the next page until it doesn’t find one – handy for crawling blogs,
forums and other sites with pagination.
Another common pattern is to build an item with data from more than one page, using a trick to pass additional data
to the callbacks.
Note: As an example spider that leverages this mechanism, check out the CrawlSpider class for a generic spider
that implements a small rules engine that you can use to write your crawlers on top of it.
The simplest way to store the scraped data is by using Feed exports, with the following command:
That will generate an items.json file containing all scraped items, serialized in JSON.
In small projects (like the one in this tutorial), that should be enough. However, if you want to perform more complex
things with the scraped items, you can write an Item Pipeline. As with Items, a placeholder file for Item Pipelines
has been set up for you when the project is created, in tutorial/pipelines.py. Though you don’t need to
implement any item pipelines if you just want to store the scraped items.
Next steps
This tutorial covered only the basics of Scrapy, but there’s a lot of other features not mentioned here. Check the What
else? section in Scrapy at a glance chapter for a quick overview of the most important ones.
Then, we recommend you continue by playing with an example project (see Examples), and then continue with the
section Basic concepts.
Examples
The best way to learn is with examples, and Scrapy is no exception. For this reason, there is an example Scrapy project
named dirbot, that you can use to play and learn more about Scrapy. It contains the dmoz spider described in the
tutorial.
This dirbot project is available at: https://github.com/scrapy/dirbot
It contains a README file with a detailed description of the project contents.
If you’re familiar with git, you can checkout the code. Otherwise you can download a tarball or zip file of the project
by clicking on Downloads.
The scrapy tag on Snipplr is used for sharing code snippets such as spiders, middlewares, extensions, or scripts. Feel
free (and encouraged!) to share any code there.
Scrapy at a glance Understand what Scrapy is and how it can help you.
2.4. Examples 19
Scrapy Documentation, Release 1.0.7
Basic concepts
Configuration settings
Scrapy will look for configuration parameters in ini-style scrapy.cfg files in standard locations:
1. /etc/scrapy.cfg or c:\scrapy\scrapy.cfg (system-wide),
2. ~/.config/scrapy.cfg ($XDG_CONFIG_HOME) and ~/.scrapy.cfg ($HOME) for global (user-
wide) settings, and
3. scrapy.cfg inside a scrapy project’s root (see next section).
Settings from these files are merged in the listed order of preference: user-defined values have higher priority than
system-wide defaults and project-wide settings will override all others, when defined.
Scrapy also understands, and can be configured through, a number of environment variables. Currently these are:
• SCRAPY_SETTINGS_MODULE (See Designating the settings)
• SCRAPY_PROJECT
21
Scrapy Documentation, Release 1.0.7
Before delving into the command-line tool and its sub-commands, let’s first understand the directory structure of a
Scrapy project.
Though it can be modified, all Scrapy projects have the same file structure by default, similar to this:
scrapy.cfg
myproject/
__init__.py
items.py
pipelines.py
settings.py
spiders/
__init__.py
spider1.py
spider2.py
...
The directory where the scrapy.cfg file resides is known as the project root directory. That file contains the name
of the python module that defines the project settings. Here is an example:
[settings]
default = myproject.settings
You can start by running the Scrapy tool with no arguments and it will print some usage help and the available
commands:
Usage:
scrapy <command> [options] [args]
Available commands:
crawl Run a spider
fetch Fetch a URL using the Scrapy downloader
[...]
The first line will print the currently active project if you’re inside a Scrapy project. In this example it was run from
outside a project. If run from inside a project it would have printed something like this:
Usage:
scrapy <command> [options] [args]
[...]
Creating projects
The first thing you typically do with the scrapy tool is create your Scrapy project:
And you’re ready to use the scrapy command to manage and control your project from there.
Controlling projects
You use the scrapy tool from inside your projects to control and manage them.
For example, to create a new spider:
scrapy genspider mydomain mydomain.com
Some Scrapy commands (like crawl) must be run from inside a Scrapy project. See the commands reference below
for more information on which commands must be run from inside projects, and which not.
Also keep in mind that some commands may have slightly different behaviours when running them from inside
projects. For example, the fetch command will use spider-overridden behaviours (such as the user_agent attribute
to override the user-agent) if the url being fetched is associated with some specific spider. This is intentional, as the
fetch command is meant to be used to check how spiders are downloading pages.
This section contains a list of the available built-in commands with a description and some usage examples. Remember,
you can always get more info about each command by running:
scrapy <command> -h
There are two kinds of commands, those that only work from inside a Scrapy project (Project-specific commands) and
those that also work without an active Scrapy project (Global commands), though they may behave slightly different
when running from inside a project (as they would use the project overridden settings).
Global commands:
• startproject
• settings
• runspider
• shell
• fetch
• view
• version
Project-only commands:
• crawl
• check
• list
• edit
• parse
• genspider
• bench
startproject
genspider
$ scrapy genspider -l
Available templates:
basic
crawl
csvfeed
xmlfeed
class $classname(scrapy.Spider):
name = "$name"
allowed_domains = ["$domain"]
start_urls = (
'http://www.$domain/',
)
crawl
check
$ scrapy check -l
first_spider
* parse
* parse_item
second_spider
* parse
* parse_item
$ scrapy check
[FAILED] first_spider:parse_item
>>> 'RetailPricex' field is missing
[FAILED] first_spider:parse
>>> Returned 92 requests, expected 0..4
list
$ scrapy list
spider1
spider2
edit
Edit the given spider using the editor defined in the EDITOR setting.
This command is provided only as a convenience shortcut for the most common case, the developer is of course free
to choose any tool or IDE to write and debug his spiders.
Usage example:
fetch
view
shell
parse
# Requests -----------------------------------------------------------------
[]
settings
runspider
version
bench
You can also add your custom project commands by using the COMMANDS_MODULE setting. See the Scrapy com-
mands in scrapy/commands for examples on how to implement your commands.
COMMANDS_MODULE
COMMANDS_MODULE = 'mybot.commands'
You can also add Scrapy commands from an external library by adding a scrapy.commands section in the entry
points of the library setup.py file.
The following example adds my_command command:
setup(name='scrapy-mymodule',
entry_points={
'scrapy.commands': [
'my_command=my_scrapy_module.commands:MyCommand',
],
},
)
Spiders
Spiders are classes which define how a certain site (or a group of sites) will be scraped, including how to perform
the crawl (i.e. follow links) and how to extract structured data from their pages (i.e. scraping items). In other words,
Spiders are the place where you define the custom behaviour for crawling and parsing pages for a particular site (or,
in some cases, a group of sites).
For spiders, the scraping cycle goes through something like this:
1. You start by generating the initial Requests to crawl the first URLs, and specify a callback function to be called
with the response downloaded from those requests.
The first requests to perform are obtained by calling the start_requests() method which (by default)
generates Request for the URLs specified in the start_urls and the parse method as callback function
for the Requests.
2. In the callback function, you parse the response (web page) and return either dicts with extracted data, Item
objects, Request objects, or an iterable of these objects. Those Requests will also contain a callback (maybe
the same) and will then be downloaded by Scrapy and then their response handled by the specified callback.
3. In callback functions, you parse the page contents, typically using Selectors (but you can also use BeautifulSoup,
lxml or whatever mechanism you prefer) and generate items with the parsed data.
4. Finally, the items returned from the spider will be typically persisted to a database (in some Item Pipeline) or
written to a file using Feed exports.
3.2. Spiders 29
Scrapy Documentation, Release 1.0.7
Even though this cycle applies (more or less) to any kind of spider, there are different kinds of default spiders bundled
into Scrapy for different purposes. We will talk about those types here.
scrapy.Spider
class scrapy.spiders.Spider
This is the simplest spider, and the one from which every other spider must inherit (including spiders that come
bundled with Scrapy, as well as spiders that you write yourself). It doesn’t provide any special functionality. It
just provides a default start_requests() implementation which sends requests from the start_urls
spider attribute and calls the spider’s method parse for each of the resulting responses.
name
A string which defines the name for this spider. The spider name is how the spider is located (and instan-
tiated) by Scrapy, so it must be unique. However, nothing prevents you from instantiating more than one
instance of the same spider. This is the most important spider attribute and it’s required.
If the spider scrapes a single domain, a common practice is to name the spider after the domain, with
or without the TLD. So, for example, a spider that crawls mywebsite.com would often be called
mywebsite.
allowed_domains
An optional list of strings containing domains that this spider is allowed to crawl. Requests for URLs
not belonging to the domain names specified in this list won’t be followed if OffsiteMiddleware is
enabled.
start_urls
A list of URLs where the spider will begin to crawl from, when no particular URLs are specified. So,
the first pages downloaded will be those listed here. The subsequent URLs will be generated successively
from data contained in the start URLs.
custom_settings
A dictionary of settings that will be overridden from the project wide configuration when running this
spider. It must be defined as a class attribute since the settings are updated before instantiation.
For a list of available built-in settings see: Built-in settings reference.
crawler
This attribute is set by the from_crawler() class method after initializating the class, and links to the
Crawler object to which this spider instance is bound.
Crawlers encapsulate a lot of components in the project for their single entry access (such as extensions,
middlewares, signals managers, etc). See Crawler API to know more about them.
settings
Configuration for running this spider. This is a Settings instance, see the Settings topic for a detailed
introduction on this subject.
logger
Python logger created with the Spider’s name. You can use it to send log messages through it as described
on Logging from Spiders.
from_crawler(crawler, *args, **kwargs)
This is the class method used by Scrapy to create your spiders.
You probably won’t need to override this directly because the default implementation acts as a proxy to
the __init__() method, calling it with the given arguments args and named arguments kwargs.
Nonetheless, this method sets the crawler and settings attributes in the new instance so they can be
accessed later inside the spider’s code.
Parameters
• crawler (Crawler instance) – crawler to which the spider will be bound
• args (list) – arguments passed to the __init__() method
• kwargs (dict) – keyword arguments passed to the __init__() method
start_requests()
This method must return an iterable with the first Requests to crawl for this spider.
This is the method called by Scrapy when the spider is opened for scraping when no particular URLs
are specified. If particular URLs are specified, the make_requests_from_url() is used instead to
create the Requests. This method is also called only once from Scrapy, so it’s safe to implement it as a
generator.
The default implementation uses make_requests_from_url() to generate Requests for each url in
start_urls.
If you want to change the Requests used to start scraping a domain, this is the method to override. For
example, if you need to start by logging in using a POST request, you could do:
class MySpider(scrapy.Spider):
name = 'myspider'
def start_requests(self):
return [scrapy.FormRequest("http://www.example.com/login",
formdata={'user': 'john', 'pass': 'secret'}
˓→,
callback=self.logged_in)]
make_requests_from_url(url)
A method that receives a URL and returns a Request object (or a list of Request objects) to scrape.
This method is used to construct the initial requests in the start_requests() method, and is typically
used to convert urls to requests.
Unless overridden, this method returns Requests with the parse() method as their callback function,
and with dont_filter parameter enabled (see Request class for more info).
parse(response)
This is the default callback used by Scrapy to process downloaded responses, when their requests don’t
specify a callback.
The parse method is in charge of processing the response and returning scraped data and/or more URLs
to follow. Other Requests callbacks have the same requirements as the Spider class.
This method, as well as any other Request callback, must return an iterable of Request and/or dicts or
Item objects.
Parameters response (Response) – the response to parse
log(message[, level, component ])
Wrapper that sends a log message through the Spider’s logger, kept for backwards compatibility. For
more information see Logging from Spiders.
3.2. Spiders 31
Scrapy Documentation, Release 1.0.7
closed(reason)
Called when the spider closes. This method provides a shortcut to signals.connect() for the
spider_closed signal.
Let’s see an example:
import scrapy
class MySpider(scrapy.Spider):
name = 'example.com'
allowed_domains = ['example.com']
start_urls = [
'http://www.example.com/1.html',
'http://www.example.com/2.html',
'http://www.example.com/3.html',
]
class MySpider(scrapy.Spider):
name = 'example.com'
allowed_domains = ['example.com']
start_urls = [
'http://www.example.com/1.html',
'http://www.example.com/2.html',
'http://www.example.com/3.html',
]
Instead of start_urls you can use start_requests() directly; to give data more structure you can use Items:
import scrapy
from myproject.items import MyItem
class MySpider(scrapy.Spider):
name = 'example.com'
allowed_domains = ['example.com']
def start_requests(self):
yield scrapy.Request('http://www.example.com/1.html', self.parse)
yield scrapy.Request('http://www.example.com/2.html', self.parse)
yield scrapy.Request('http://www.example.com/3.html', self.parse)
Spider arguments
Spiders can receive arguments that modify their behaviour. Some common uses for spider arguments are to define the
start URLs or to restrict the crawl to certain sections of the site, but they can be used to configure any functionality of
the spider.
Spider arguments are passed through the crawl command using the -a option. For example:
import scrapy
class MySpider(scrapy.Spider):
name = 'myspider'
Spider arguments can also be passed through the Scrapyd schedule.json API. See Scrapyd documentation.
Generic Spiders
Scrapy comes with some useful generic spiders that you can use to subclass your spiders from. Their aim is to provide
convenient functionality for a few common scraping cases, like following all links on a site based on certain rules,
crawling from Sitemaps, or parsing an XML/CSV feed.
For the examples used in the following spiders, we’ll assume you have a project with a TestItem declared in a
myproject.items module:
import scrapy
class TestItem(scrapy.Item):
id = scrapy.Field()
name = scrapy.Field()
description = scrapy.Field()
CrawlSpider
class scrapy.spiders.CrawlSpider
This is the most commonly used spider for crawling regular websites, as it provides a convenient mechanism for
following links by defining a set of rules. It may not be the best suited for your particular web sites or project,
but it’s generic enough for several cases, so you can start from it and override it as needed for more custom
functionality, or just implement your own spider.
Apart from the attributes inherited from Spider (that you must specify), this class supports a new attribute:
3.2. Spiders 33
Scrapy Documentation, Release 1.0.7
rules
Which is a list of one (or more) Rule objects. Each Rule defines a certain behaviour for crawling the
site. Rules objects are described below. If multiple rules match the same link, the first one will be used,
according to the order they’re defined in this attribute.
This spider also exposes an overrideable method:
parse_start_url(response)
This method is called for the start_urls responses. It allows to parse the initial responses and must return
either an Item object, a Request object, or an iterable containing any of them.
Crawling rules
Warning: When writing crawl spider rules, avoid using parse as callback, since the CrawlSpider uses
the parse method itself to implement its logic. So if you override the parse method, the crawl spider will
no longer work.
cb_kwargs is a dict containing the keyword arguments to be passed to the callback function.
follow is a boolean which specifies if links should be followed from each response extracted with this rule. If
callback is None follow defaults to True, otherwise it defaults to False.
process_links is a callable, or a string (in which case a method from the spider object with that name
will be used) which will be called for each list of links extracted from each response using the specified
link_extractor. This is mainly used for filtering purposes.
process_request is a callable, or a string (in which case a method from the spider object with that name
will be used) which will be called with every request extracted by this rule, and must return a request or None
(to filter out the request).
CrawlSpider example
class MySpider(CrawlSpider):
name = 'example.com'
allowed_domains = ['example.com']
start_urls = ['http://www.example.com']
rules = (
# Extract links matching 'category.php' (but not matching 'subsection.php')
# and follow links from them (since no callback means follow=True by default).
# Extract links matching 'item.php' and parse them with the spider's method
˓→ parse_item
Rule(LinkExtractor(allow=('item\.php', )), callback='parse_item'),
)
return item
This spider would start crawling example.com’s home page, collecting category links, and item links, parsing the latter
with the parse_item method. For each item response, some data will be extracted from the HTML using XPath,
and an Item will be filled with it.
XMLFeedSpider
class scrapy.spiders.XMLFeedSpider
XMLFeedSpider is designed for parsing XML feeds by iterating through them by a certain node name. The
iterator can be chosen from: iternodes, xml, and html. It’s recommended to use the iternodes iterator
for performance reasons, since the xml and html iterators generate the whole DOM at once in order to parse
it. However, using html as the iterator may be useful when parsing XML with bad markup.
To set the iterator and the tag name, you must define the following class attributes:
iterator
A string which defines the iterator to use. It can be either:
•'iternodes' - a fast iterator based on regular expressions
•'html' - an iterator which uses Selector. Keep in mind this uses DOM parsing and must load
all DOM in memory which could be a problem for big feeds
•'xml' - an iterator which uses Selector. Keep in mind this uses DOM parsing and must load all
DOM in memory which could be a problem for big feeds
It defaults to: 'iternodes'.
itertag
A string with the name of the node (or element) to iterate in. Example:
itertag = 'product'
namespaces
A list of (prefix, uri) tuples which define the namespaces available in that document that will be
processed with this spider. The prefix and uri will be used to automatically register namespaces using
the register_namespace() method.
You can then specify nodes with namespaces in the itertag attribute.
Example:
3.2. Spiders 35
Scrapy Documentation, Release 1.0.7
class YourSpider(XMLFeedSpider):
Apart from these new attributes, this spider has the following overrideable methods too:
adapt_response(response)
A method that receives the response as soon as it arrives from the spider middleware, before the spider
starts parsing it. It can be used to modify the response body before parsing it. This method receives a
response and also returns a response (it could be the same or another one).
parse_node(response, selector)
This method is called for the nodes matching the provided tag name (itertag). Receives the response
and an Selector for each node. Overriding this method is mandatory. Otherwise, you spider won’t
work. This method must return either a Item object, a Request object, or an iterable containing any of
them.
process_results(response, results)
This method is called for each result (item or request) returned by the spider, and it’s intended to perform
any last time processing required before returning the results to the framework core, for example setting
the item IDs. It receives a list of results and the response which originated those results. It must return a
list of results (Items or Requests).
XMLFeedSpider example
These spiders are pretty easy to use, let’s have a look at one example:
class MySpider(XMLFeedSpider):
name = 'example.com'
allowed_domains = ['example.com']
start_urls = ['http://www.example.com/feed.xml']
iterator = 'iternodes' # This is actually unnecessary, since it's the default
˓→value
itertag = 'item'
item = TestItem()
item['id'] = node.xpath('@id').extract()
item['name'] = node.xpath('name').extract()
item['description'] = node.xpath('description').extract()
return item
Basically what we did up there was to create a spider that downloads a feed from the given start_urls, and then
iterates through each of its item tags, prints them out, and stores some random data in an Item.
CSVFeedSpider
class scrapy.spiders.CSVFeedSpider
This spider is very similar to the XMLFeedSpider, except that it iterates over rows, instead of nodes. The method
that gets called in each iteration is parse_row().
delimiter
A string with the separator character for each field in the CSV file Defaults to ',' (comma).
quotechar
A string with the enclosure character for each field in the CSV file Defaults to '"' (quotation mark).
headers
A list of the rows contained in the file CSV feed which will be used to extract fields from it.
parse_row(response, row)
Receives a response and a dict (representing each row) with a key for each provided (or detected)
header of the CSV file. This spider also gives the opportunity to override adapt_response and
process_results methods for pre- and post-processing purposes.
CSVFeedSpider example
Let’s see an example similar to the previous one, but using a CSVFeedSpider:
from scrapy.spiders import CSVFeedSpider
from myproject.items import TestItem
class MySpider(CSVFeedSpider):
name = 'example.com'
allowed_domains = ['example.com']
start_urls = ['http://www.example.com/feed.csv']
delimiter = ';'
quotechar = "'"
headers = ['id', 'name', 'description']
item = TestItem()
item['id'] = row['id']
item['name'] = row['name']
item['description'] = row['description']
return item
SitemapSpider
class scrapy.spiders.SitemapSpider
SitemapSpider allows you to crawl a site by discovering the URLs using Sitemaps.
It supports nested sitemaps and discovering sitemap urls from robots.txt.
sitemap_urls
A list of urls pointing to the sitemaps whose urls you want to crawl.
You can also point to a robots.txt and it will be parsed to extract sitemap urls from it.
sitemap_rules
A list of tuples (regex, callback) where:
3.2. Spiders 37
Scrapy Documentation, Release 1.0.7
•regex is a regular expression to match urls extracted from sitemaps. regex can be either a str or a
compiled regex object.
•callback is the callback to use for processing the urls that match the regular expression. callback
can be a string (indicating the name of a spider method) or a callable.
For example:
Rules are applied in order, and only the first one that matches will be used.
If you omit this attribute, all urls found in sitemaps will be processed with the parse callback.
sitemap_follow
A list of regexes of sitemap that should be followed. This is is only for sites that use Sitemap index files
that point to other sitemap files.
By default, all sitemaps are followed.
sitemap_alternate_links
Specifies if alternate links for one url should be followed. These are links for the same website in another
language passed within the same url block.
For example:
<url>
<loc>http://example.com/</loc>
<xhtml:link rel="alternate" hreflang="de" href="http://example.com/de"/>
</url>
SitemapSpider examples
Simplest example: process all urls discovered through sitemaps using the parse callback:
class MySpider(SitemapSpider):
sitemap_urls = ['http://www.example.com/sitemap.xml']
Process some urls with certain callback and other urls with a different callback:
class MySpider(SitemapSpider):
sitemap_urls = ['http://www.example.com/sitemap.xml']
sitemap_rules = [
('/product/', 'parse_product'),
('/category/', 'parse_category'),
]
Follow sitemaps defined in the robots.txt file and only follow sitemaps whose url contains /sitemap_shop:
class MySpider(SitemapSpider):
sitemap_urls = ['http://www.example.com/robots.txt']
sitemap_rules = [
('/shop/', 'parse_shop'),
]
sitemap_follow = ['/sitemap_shops']
class MySpider(SitemapSpider):
sitemap_urls = ['http://www.example.com/robots.txt']
sitemap_rules = [
('/shop/', 'parse_shop'),
]
other_urls = ['http://www.example.com/about']
def start_requests(self):
requests = list(super(MySpider, self).start_requests())
requests += [scrapy.Request(x, self.parse_other) for x in self.other_urls]
return requests
Selectors
When you’re scraping web pages, the most common task you need to perform is to extract data from the HTML source.
There are several libraries available to achieve this:
• BeautifulSoup is a very popular web scraping library among Python programmers which constructs a Python
object based on the structure of the HTML code and also deals with bad markup reasonably well, but it has one
drawback: it’s slow.
• lxml is an XML parsing library (which also parses HTML) with a pythonic API based on ElementTree. (lxml is
not part of the Python standard library.)
3.3. Selectors 39
Scrapy Documentation, Release 1.0.7
Scrapy comes with its own mechanism for extracting data. They’re called selectors because they “select” certain parts
of the HTML document specified either by XPath or CSS expressions.
XPath is a language for selecting nodes in XML documents, which can also be used with HTML. CSS is a language
for applying styles to HTML documents. It defines selectors to associate those styles with specific HTML elements.
Scrapy selectors are built over the lxml library, which means they’re very similar in speed and parsing accuracy.
This page explains how selectors work and describes their API which is very small and simple, unlike the lxml API
which is much bigger because the lxml library can be used for many other tasks, besides selecting markup documents.
For a complete reference of the selectors API see Selector reference
Using selectors
Constructing selectors
Scrapy selectors are instances of Selector class constructed by passing text or TextResponse object. It auto-
matically chooses the best parsing rules (XML vs HTML) based on input type:
For convenience, response objects expose a selector on .selector attribute, it’s totally OK to use this shortcut when
possible:
>>> response.selector.xpath('//span/text()').extract()
[u'good']
Using selectors
To explain how to use the selectors we’ll use the Scrapy shell (which provides interactive testing) and an example page
located in the Scrapy documentation server:
http://doc.scrapy.org/en/latest/_static/selectors-sample1.html
Here’s its HTML code:
<html>
<head>
<base href='http://example.com/' />
<title>Example website</title>
</head>
<body>
<div id='images'>
Then, after the shell loads, you’ll have the response available as response shell variable, and its attached selector in
response.selector attribute.
Since we’re dealing with HTML, the selector will automatically use an HTML parser.
So, by looking at the HTML code of that page, let’s construct an XPath for selecting the text inside the title tag:
>>> response.selector.xpath('//title/text()')
[<Selector (text) xpath=//title/text()>]
Querying responses using XPath and CSS is so common that responses include two convenience shortcuts:
response.xpath() and response.css():
>>> response.xpath('//title/text()')
[<Selector (text) xpath=//title/text()>]
>>> response.css('title::text')
[<Selector (text) xpath=//title/text()>]
As you can see, .xpath() and .css() methods return a SelectorList instance, which is a list of new selectors.
This API can be used for quickly selecting nested data:
>>> response.css('img').xpath('@src').extract()
[u'image1_thumb.jpg',
u'image2_thumb.jpg',
u'image3_thumb.jpg',
u'image4_thumb.jpg',
u'image5_thumb.jpg']
To actually extract the textual data, you must call the selector .extract() method, as follows:
>>> response.xpath('//title/text()').extract()
[u'Example website']
If you want to extract only first matched element, you can call the selector .extract_first()
>>> response.xpath('//div[@id="images"]/a/text()').extract_first()
u'Name: My image 1 '
3.3. Selectors 41
Scrapy Documentation, Release 1.0.7
>>> response.xpath('//div[@id="not-exists"]/text()').extract_first(default='not-found
˓→')
'not-found'
Notice that CSS selectors can select text or attribute nodes using CSS3 pseudo-elements:
>>> response.css('title::text').extract()
[u'Example website']
Now we’re going to get the base URL and some image links:
>>> response.xpath('//base/@href').extract()
[u'http://example.com/']
>>> response.css('base::attr(href)').extract()
[u'http://example.com/']
>>> response.css('a[href*=image]::attr(href)').extract()
[u'image1.html',
u'image2.html',
u'image3.html',
u'image4.html',
u'image5.html']
Nesting selectors
The selection methods (.xpath() or .css()) return a list of selectors of the same type, so you can call the selection
methods for those selectors too. Here’s an example:
... print 'Link number %d points to url %s and image %s' % args
Selector also has a .re() method for extracting data using regular expressions. However, unlike using .
xpath() or .css() methods, .re() returns a list of unicode strings. So you can’t construct nested .re()
calls.
Here’s an example used to extract image names from the HTML code above:
There’s an additional helper reciprocating .extract_first() for .re(), named .re_first(). Use it to
extract just the first matching string:
Keep in mind that if you are nesting selectors and use an XPath that starts with /, that XPath will be absolute to the
document and not relative to the Selector you’re calling it from.
For example, suppose you want to extract all <p> elements inside <div> elements. First, you would get all <div>
elements:
At first, you may be tempted to use the following approach, which is wrong, as it actually extracts all <p> elements
from the document, not only those inside <div> elements:
>>> for p in divs.xpath('//p'): # this is wrong - gets all <p> from the whole
˓→document
This is the proper way to do it (note the dot prefixing the .//p XPath):
3.3. Selectors 43
Scrapy Documentation, Release 1.0.7
For more details about relative XPaths see the Location Paths section in the XPath specification.
Being built atop lxml, Scrapy selectors also support some EXSLT extensions and come with these pre-registered
namespaces to use in XPath expressions:
prefix namespace usage
re http://exslt.org/regular-expressions regular expressions
set http://exslt.org/sets set manipulation
Regular expressions
The test() function, for example, can prove quite useful when XPath’s starts-with() or contains() are
not sufficient.
Example selecting links in list item with a “class” attribute ending with a digit:
Warning: C library libxslt doesn’t natively support EXSLT regular expressions so lxml‘s implementation
uses hooks to Python’s re module. Thus, using regexp functions in your XPath expressions may add a small
performance penalty.
Set operations
These can be handy for excluding parts of a document tree before extracting text elements for example.
Example extracting microdata (sample content taken from http://schema.org/Product) with groups of itemscopes and
corresponding itemprops:
3.3. Selectors 45
Scrapy Documentation, Release 1.0.7
>>>
Here we first iterate over itemscope elements, and for each one, we look for all itemprops elements and exclude
those that are themselves inside another itemscope.
Here are some tips that you may find useful when using XPath with Scrapy selectors, based on this post from Scrap-
ingHub’s blog. If you are not much familiar with XPath yet, you may want to take a look first at this XPath tutorial.
When you need to use the text content as argument to an XPath string function, avoid using .//text() and use just
. instead.
This is because the expression .//text() yields a collection of text elements – a node-set. And when a node-
set is converted to a string, which happens when it is passed as argument to a string function like contains() or
starts-with(), it results in the text for the first element only.
Example:
>>> from scrapy import Selector
>>> sel = Selector(text='<a href="#">Click here to go to the <strong>Next Page</
˓→strong></a>')
A node converted to a string, however, puts together the text of itself plus of all its descendants:
So, using the .//text() node-set won’t select anything in this case:
//node[1] selects all the nodes occurring first under their respective parents.
(//node)[1] selects all the nodes in the document, and then gets only the first of them.
Example:
This gets all first <li> elements under whatever it is its parent:
>>> xp("//li[1]")
[u'<li>1</li>', u'<li>4</li>']
And this gets the first <li> element in the whole document:
>>> xp("(//li)[1]")
[u'<li>1</li>']
>>> xp("//ul/li[1]")
[u'<li>1</li>', u'<li>4</li>']
And this gets the first <li> element under an <ul> parent in the whole document:
3.3. Selectors 47
Scrapy Documentation, Release 1.0.7
>>> xp("(//ul/li)[1]")
[u'<li>1</li>']
Because an element can contain multiple CSS classes, the XPath way to select elements by class is the rather verbose:
If you use @class='someclass' you may end up missing elements that have other classes, and if you just use
contains(@class, 'someclass') to make up for that you may end up with more elements that you want, if
they have a different class name that shares the string someclass.
As it turns out, Scrapy selectors allow you to chain selectors, so most of the time you can just select by class using
CSS and then switch to XPath when needed:
>>> sel.css('.shout').xpath('./time/@datetime').extract()
[u'2014-07-23 19:00']
This is cleaner than using the verbose XPath trick shown above. Just remember to use the . in the XPath expressions
that will follow.
css(query)
Apply the given CSS selector and return a SelectorList instance.
query is a string containing the CSS selector to apply.
In the background, CSS queries are translated into XPath queries using cssselect library and run .
xpath() method.
extract()
Serialize and return the matched nodes as a list of unicode strings. Percent encoded content is unquoted.
re(regex)
Apply the given regex and return a list of unicode strings with the matches.
regex can be either a compiled regular expression or a string which will be compiled to a regular expres-
sion using re.compile(regex)
register_namespace(prefix, uri)
Register the given namespace to be used in this Selector. Without registering namespaces you can’t
select or extract data from non-standard namespaces. See examples below.
remove_namespaces()
Remove all namespaces, allowing to traverse the document using namespace-less xpaths. See example
below.
__nonzero__()
Returns True if there is any real content selected or False otherwise. In other words, the boolean value
of a Selector is given by the contents it selects.
SelectorList objects
class scrapy.selector.SelectorList
The SelectorList class is a subclass of the builtin list class, which provides a few additional methods.
xpath(query)
Call the .xpath() method for each element in this list and return their results flattened as another
SelectorList.
query is the same argument as the one in Selector.xpath()
css(query)
Call the .css() method for each element in this list and return their results flattened as another
SelectorList.
query is the same argument as the one in Selector.css()
extract()
Call the .extract() method for each element in this list and return their results flattened, as a list of
unicode strings.
re()
Call the .re() method for each element in this list and return their results flattened, as a list of unicode
strings.
3.3. Selectors 49
Scrapy Documentation, Release 1.0.7
__nonzero__()
returns True if the list is not empty, False otherwise.
Here’s a couple of Selector examples to illustrate several concepts. In all cases, we assume there is already a
Selector instantiated with a HtmlResponse object like this:
sel = Selector(html_response)
1. Select all <h1> elements from an HTML response body, returning a list of Selector objects (ie. a
SelectorList object):
sel.xpath("//h1")
2. Extract the text of all <h1> elements from an HTML response body, returning a list of unicode strings:
3. Iterate over all <p> tags and print their class attribute:
Here’s a couple of examples to illustrate several concepts. In both cases we assume there is already a Selector
instantiated with an XmlResponse object like this:
sel = Selector(xml_response)
1. Select all <product> elements from an XML response body, returning a list of Selector objects (ie. a
SelectorList object):
sel.xpath("//product")
2. Extract all prices from a Google Base XML feed which requires registering a namespace:
sel.register_namespace("g", "http://base.google.com/ns/1.0")
sel.xpath("//g:price").extract()
Removing namespaces
When dealing with scraping projects, it is often quite convenient to get rid of namespaces altogether and just work with
element names, to write more simple/convenient XPaths. You can use the Selector.remove_namespaces()
method for that.
Let’s show an example that illustrates this with Github blog atom feed.
First, we open the shell with the url we want to scrape:
Once in the shell we can try selecting all <link> objects and see that it doesn’t work (because the Atom XML
namespace is obfuscating those nodes):
>>> response.xpath("//link")
[]
But once we call the Selector.remove_namespaces() method, all nodes can be accessed directly by their
names:
>>> response.selector.remove_namespaces()
>>> response.xpath("//link")
[<Selector xpath='//link' data=u'<link xmlns="http://www.w3.org/2005/Atom'>,
<Selector xpath='//link' data=u'<link xmlns="http://www.w3.org/2005/Atom'>,
...
If you wonder why the namespace removal procedure isn’t always called by default instead of having to call it manu-
ally, this is because of two reasons, which, in order of relevance, are:
1. Removing namespaces requires to iterate and modify all nodes in the document, which is a reasonably expensive
operation to perform for all documents crawled by Scrapy
2. There could be some cases where using namespaces is actually required, in case some element names clash
between namespaces. These cases are very rare though.
Items
The main goal in scraping is to extract structured data from unstructured sources, typically, web pages. Scrapy spiders
can return the extracted data as Python dicts. While convenient and familiar, Python dicts lack structure: it is easy to
make a typo in a field name or return inconsistent data, especially in a larger project with many spiders.
To define common output data format Scrapy provides the Item class. Item objects are simple containers used to
collect the scraped data. They provide a dictionary-like API with a convenient syntax for declaring their available
fields.
Various Scrapy components use extra information provided by Items: exporters look at declared fields to figure out
columns to export, serialization can be customized using Item fields metadata, trackref tracks Item instances to
help finding memory leaks (see Debugging memory leaks with trackref ), etc.
Declaring Items
Items are declared using a simple class definition syntax and Field objects. Here is an example:
import scrapy
class Product(scrapy.Item):
name = scrapy.Field()
price = scrapy.Field()
stock = scrapy.Field()
last_updated = scrapy.Field(serializer=str)
3.4. Items 51
Scrapy Documentation, Release 1.0.7
Note: Those familiar with Django will notice that Scrapy Items are declared similar to Django Models, except that
Scrapy Items are much simpler as there is no concept of different field types.
Item Fields
Field objects are used to specify metadata for each field. For example, the serializer function for the
last_updated field illustrated in the example above.
You can specify any kind of metadata for each field. There is no restriction on the values accepted by Field objects.
For this same reason, there is no reference list of all available metadata keys. Each key defined in Field objects
could be used by a different component, and only those components know about it. You can also define and use any
other Field key in your project too, for your own needs. The main goal of Field objects is to provide a way to
define all field metadata in one place. Typically, those components whose behaviour depends on each field use certain
field keys to configure that behaviour. You must refer to their documentation to see which metadata keys are used by
each component.
It’s important to note that the Field objects used to declare the item do not stay assigned as class attributes. Instead,
they can be accessed through the Item.fields attribute.
Here are some examples of common tasks performed with items, using the Product item declared above. You will
notice the API is very similar to the dict API.
Creating items
>>> product['name']
Desktop PC
>>> product.get('name')
Desktop PC
>>> product['price']
1000
>>> product['last_updated']
Traceback (most recent call last):
...
KeyError: 'last_updated'
...
KeyError: 'lala'
To access all populated values, just use the typical dict API:
>>> product.keys()
['price', 'name']
>>> product.items()
[('price', 1000), ('name', 'Desktop PC')]
Copying items:
3.4. Items 53
Scrapy Documentation, Release 1.0.7
>>> Product({'name': 'Laptop PC', 'lala': 1500}) # warning: unknown field in dict
Traceback (most recent call last):
...
KeyError: 'Product does not support field: lala'
Extending Items
You can extend Items (to add more fields or to change some metadata for some fields) by declaring a subclass of your
original Item.
For example:
class DiscountedProduct(Product):
discount_percent = scrapy.Field(serializer=str)
discount_expiration_date = scrapy.Field()
You can also extend field metadata by using the previous field metadata and appending more values, or changing
existing values, like this:
class SpecificProduct(Product):
name = scrapy.Field(Product.fields['name'], serializer=my_serializer)
That adds (or replaces) the serializer metadata key for the name field, keeping all the previously existing meta-
data values.
Item objects
class scrapy.item.Item([arg ])
Return a new Item optionally initialized from the given argument.
Items replicate the standard dict API, including its constructor. The only additional attribute provided by Items
is:
fields
A dictionary containing all declared fields for this Item, not only those populated. The keys are the field
names and the values are the Field objects used in the Item declaration.
Field objects
class scrapy.item.Field([arg ])
The Field class is just an alias to the built-in dict class and doesn’t provide any extra functionality or at-
tributes. In other words, Field objects are plain-old Python dicts. A separate class is used to support the item
declaration syntax based on class attributes.
Item Loaders
Item Loaders provide a convenient mechanism for populating scraped Items. Even though Items can be populated
using their own dictionary-like API, Item Loaders provide a much more convenient API for populating them from a
scraping process, by automating some common tasks like parsing the raw extracted data before assigning it.
In other words, Items provide the container of scraped data, while Item Loaders provide the mechanism for populating
that container.
Item Loaders are designed to provide a flexible, efficient and easy mechanism for extending and overriding different
field parsing rules, either by spider, or by source format (HTML, XML, etc) without becoming a nightmare to maintain.
To use an Item Loader, you must first instantiate it. You can either instantiate it with a dict-like object (e.g. Item or
dict) or without one, in which case an Item is automatically instantiated in the Item Loader constructor using the Item
class specified in the ItemLoader.default_item_class attribute.
Then, you start collecting values into the Item Loader, typically using Selectors. You can add more than one value to
the same item field; the Item Loader will know how to “join” those values later using a proper processing function.
Here is a typical Item Loader usage in a Spider, using the Product item declared in the Items chapter:
By quickly looking at that code, we can see the name field is being extracted from two different XPath locations in
the page:
1. //div[@class="product_name"]
2. //div[@class="product_title"]
In other words, data is being collected by extracting it from two XPath locations, using the add_xpath() method.
This is the data that will be assigned to the name field later.
Afterwards, similar calls are used for price and stock fields (the later using a CSS selector with the add_css()
method), and finally the last_update field is populated directly with a literal value (today) using a different
method: add_value().
Finally, when all data is collected, the ItemLoader.load_item() method is called which actually returns
the item populated with the data previously extracted and collected with the add_xpath(), add_css(), and
add_value() calls.
An Item Loader contains one input processor and one output processor for each (item) field. The input processor
processes the extracted data as soon as it’s received (through the add_xpath(), add_css() or add_value()
methods) and the result of the input processor is collected and kept inside the ItemLoader. After collecting all data,
the ItemLoader.load_item() method is called to populate and get the populated Item object. That’s when the
output processor is called with the data previously collected (and processed using the input processor). The result of
the output processor is the final value that gets assigned to the item.
Let’s see an example to illustrate how the input and output processors are called for a particular field (the same applies
for any other field):
l = ItemLoader(Product(), some_selector)
l.add_xpath('name', xpath1) # (1)
l.add_xpath('name', xpath2) # (2)
l.add_css('name', css) # (3)
l.add_value('name', 'test') # (4)
return l.load_item() # (5)
Note: Both input and output processors must receive an iterator as their first argument. The output of those functions
can be anything. The result of input processors will be appended to an internal list (in the Loader) containing the
collected values (for that field). The result of the output processors is the value that will be finally assigned to the item.
The other thing you need to keep in mind is that the values returned by input processors are collected internally (in
lists) and then passed to output processors to populate the fields.
Last, but not least, Scrapy comes with some commonly used processors built-in for convenience.
Item Loaders are declared like Items, by using a class definition syntax. Here is an example:
class ProductLoader(ItemLoader):
default_output_processor = TakeFirst()
name_in = MapCompose(unicode.title)
name_out = Join()
price_in = MapCompose(unicode.strip)
# ...
As you can see, input processors are declared using the _in suffix while output processors are declared us-
ing the _out suffix. And you can also declare a default input/output processors using the ItemLoader.
default_input_processor and ItemLoader.default_output_processor attributes.
As seen in the previous section, input and output processors can be declared in the Item Loader definition, and it’s
very common to declare input processors this way. However, there is one more place where you can specify the input
and output processors to use: in the Item Field metadata. Here is an example:
import scrapy
from scrapy.loader.processors import Join, MapCompose, TakeFirst
from w3lib.html import remove_tags
def filter_price(value):
if value.isdigit():
return value
class Product(scrapy.Item):
name = scrapy.Field(
input_processor=MapCompose(remove_tags),
output_processor=Join(),
)
price = scrapy.Field(
input_processor=MapCompose(remove_tags, filter_price),
output_processor=TakeFirst(),
)
The precedence order, for both input and output processors, is as follows:
1. Item Loader field-specific attributes: field_in and field_out (most precedence)
2. Field metadata (input_processor and output_processor key)
3. Item Loader defaults: ItemLoader.default_input_processor() and ItemLoader.
default_output_processor() (least precedence)
See also: Reusing and extending Item Loaders.
The Item Loader Context is a dict of arbitrary key/values which is shared among all input and output processors in
the Item Loader. It can be passed when declaring, instantiating or using Item Loader. They are used to modify the
behaviour of the input/output processors.
For example, suppose you have a function parse_length which receives a text value and extracts a length from it:
By accepting a loader_context argument the function is explicitly telling the Item Loader that it’s able to receive
an Item Loader context, so the Item Loader passes the currently active context when calling it, and the processor
function (parse_length in this case) can thus use them.
There are several ways to modify Item Loader context values:
1. By modifying the currently active Item Loader context (context attribute):
loader = ItemLoader(product)
loader.context['unit'] = 'cm'
2. On Item Loader instantiation (the keyword arguments of Item Loader constructor are stored in the Item Loader
context):
3. On Item Loader declaration, for those input/output processors that support instantiating them with an Item
Loader context. MapCompose is one of them:
class ProductLoader(ItemLoader):
length_out = MapCompose(parse_length, unit='cm')
ItemLoader objects
The item, selector, response and the remaining keyword arguments are assigned to the Loader context (accessible
through the context attribute).
ItemLoader instances have the following methods:
get_value(value, *processors, **kwargs)
Process the given value by the given processors and keyword arguments.
Available keyword arguments:
Parameters re (str or compiled regex) – a regular expression to use for extracting
data from the given value using extract_regex() method, applied before processors
Examples:
'FOO`
get_output_processor(field_name)
Return the output processor for the given field.
ItemLoader instances have the following attributes:
item
The Item object being parsed by this Item Loader.
context
The currently active Context of this Item Loader.
default_item_class
An Item class (or factory), used to instantiate items when not given in the constructor.
default_input_processor
The default input processor to use for those fields which don’t specify one.
default_output_processor
The default output processor to use for those fields which don’t specify one.
default_selector_class
The class used to construct the selector of this ItemLoader, if only a response is given in the
constructor. If a selector is given in the constructor this attribute is ignored. This attribute is sometimes
overridden in subclasses.
selector
The Selector object to extract data from. It’s either the selector given in the constructor or one created
from the response given in the constructor using the default_selector_class. This attribute is
meant to be read-only.
As your project grows bigger and acquires more and more spiders, maintenance becomes a fundamental problem,
especially when you have to deal with many different parsing rules for each spider, having a lot of exceptions, but also
wanting to reuse the common processors.
Item Loaders are designed to ease the maintenance burden of parsing rules, without losing flexibility and, at the same
time, providing a convenient mechanism for extending and overriding them. For this reason Item Loaders support
traditional Python class inheritance for dealing with differences of specific spiders (or groups of spiders).
Suppose, for example, that some particular site encloses their product names in three dashes (e.g. ---Plasma
TV---) and you don’t want to end up scraping those dashes in the final product names.
Here’s how you can remove those dashes by reusing and extending the default Product Item Loader
(ProductLoader):
def strip_dashes(x):
return x.strip('-')
class SiteSpecificLoader(ProductLoader):
name_in = MapCompose(strip_dashes, ProductLoader.name_in)
Another case where extending Item Loaders can be very helpful is when you have multiple source formats, for example
XML and HTML. In the XML version you may want to remove CDATA occurrences. Here’s an example of how to do
it:
class XmlProductLoader(ProductLoader):
name_in = MapCompose(remove_cdata, ProductLoader.name_in)
Even though you can use any callable function as input and output processors, Scrapy provides some commonly
used processors, which are described below. Some of them, like the MapCompose (which is typically used as input
processor) compose the output of several functions executed in order, to produce the final parsed value.
Here is a list of all built-in processors:
class scrapy.loader.processors.Identity
The simplest processor, which doesn’t do anything. It returns the original values unchanged. It doesn’t receive
any constructor arguments, nor does it accept Loader contexts.
Example:
class scrapy.loader.processors.TakeFirst
Returns the first non-null/non-empty value from the values received, so it’s typically used as an output processor
to single-valued fields. It doesn’t receive any constructor arguments, nor does it accept Loader contexts.
Example:
class scrapy.loader.processors.Join(separator=u’ ‘)
Returns the values joined with the separator given in the constructor, which defaults to u' '. It doesn’t accept
Loader contexts.
When using the default separator, this processor is equivalent to the function: u' '.join
Examples:
Each function can optionally receive a loader_context parameter. For those which do, this processor will
pass the currently active Loader context through that parameter.
The keyword arguments passed in the constructor are used as the default Loader context values passed to each
function call. However, the final Loader context values passed to functions are overridden with the currently
active Loader context accessible through the ItemLoader.context() attribute.
class scrapy.loader.processors.MapCompose(*functions, **default_loader_context)
A processor which is constructed from the composition of the given functions, similar to the Compose pro-
cessor. The difference with this processor is the way internal results are passed among functions, which is as
follows:
The input value of this processor is iterated and the first function is applied to each element. The results of these
function calls (one for each element) are concatenated to construct a new iterable, which is then used to apply
the second function, and so on, until the last function is applied to each value of the list of values collected so
far. The output values of the last function are concatenated together to produce the output of this processor.
Each particular function can return a value or a list of values, which is flattened with the list of values returned
by the same function applied to the other input values. The functions can also return None in which case the
output of that function is ignored for further processing over the chain.
This processor provides a convenient way to compose functions that only work with single values (instead of
iterables). For this reason the MapCompose processor is typically used as input processor, since data is often
extracted using the extract() method of selectors, which returns a list of unicode strings.
The example below should clarify how it works:
As with the Compose processor, functions can receive Loader contexts, and constructor keyword arguments are
used as default context values. See Compose processor for more info.
class scrapy.loader.processors.SelectJmes(json_path)
Queries the value using the json path provided to the constructor and returns the output. Requires jmespath
(https://github.com/jmespath/jmespath.py) to run. This processor takes only one input at a time.
Example:
Scrapy shell
The Scrapy shell is an interactive shell where you can try and debug your scraping code very quickly, without having
to run the spider. It’s meant to be used for testing data extraction code, but you can actually use it for testing any kind
of code as it is also a regular Python shell.
The shell is used for testing XPath or CSS expressions and see how they work and what data they extract from the web
pages you’re trying to scrape. It allows you to interactively test your expressions while you’re writing your spider,
without having to run the spider to test every change.
Once you get familiarized with the Scrapy shell, you’ll see that it’s an invaluable tool for developing and debugging
your spiders.
If you have IPython installed, the Scrapy shell will use it (instead of the standard Python console). The IPython console
is much more powerful and provides smart auto-completion and colorized output, among other things.
We highly recommend you install IPython, specially if you’re working on Unix systems (where IPython excels). See
the IPython installation guide for more info.
To launch the Scrapy shell you can use the shell command like this:
The Scrapy shell is just a regular Python console (or IPython console if you have it available) which provides some
additional shortcut functions for convenience.
Available Shortcuts
• shelp() - print a help with the list of available objects and shortcuts
• fetch(request_or_url) - fetch a new response from the given request or URL and update all related
objects accordingly.
• view(response) - open the given response in your local web browser, for inspection. This will add a <base>
tag to the response body in order for external links (such as images and style sheets) to display properly. Note,
however, that this will create a temporary file in your computer, which won’t be removed automatically.
The Scrapy shell automatically creates some convenient objects from the downloaded page, like the Response object
and the Selector objects (for both HTML and XML content).
Those objects are:
• crawler - the current Crawler object.
• spider - the Spider which is known to handle the URL, or a Spider object if there is no spider found for the
current URL
• request - a Request object of the last fetched page. You can modify this request using replace() or
fetch a new request (without leaving the shell) using the fetch shortcut.
• response - a Response object containing the last fetched page
• settings - the current Scrapy settings
Here’s an example of a typical shell session where we start by scraping the http://scrapy.org page, and then proceed to
scrape the http://slashdot.org page. Finally, we modify the (Slashdot) request method to POST and re-fetch it getting a
HTTP 405 (method not allowed) error. We end the session by typing Ctrl-D (in Unix systems) or Ctrl-Z in Windows.
Keep in mind that the data extracted here may not be the same when you try it, as those pages are not static and could
have changed by the time you test this. The only purpose of this example is to get you familiarized with how the
Scrapy shell works.
First, we launch the shell:
Then, the shell fetches the URL (using the Scrapy downloader) and prints the list of available objects and useful
shortcuts (you’ll notice that these lines all start with the [s] prefix):
>>>
>>> fetch("http://slashdot.org")
[s] Available Scrapy objects:
[s] crawler <scrapy.crawler.Crawler object at 0x1a13b50>
[s] item {}
[s] request <GET http://slashdot.org>
[s] response <200 http://slashdot.org>
[s] settings <scrapy.settings.Settings object at 0x2bfd650>
[s] spider <Spider 'default' at 0x20c6f50>
[s] Useful shortcuts:
[s] shelp() Shell help (print this help)
[s] fetch(req_or_url) Fetch request (or URL) and update local objects
[s] view(response) View response in a browser
>>> response.xpath('//title/text()').extract()
[u'Slashdot: News for nerds, stuff that matters']
>>> fetch(request)
[s] Available Scrapy objects:
[s] crawler <scrapy.crawler.Crawler object at 0x1e16b50>
...
>>>
Sometimes you want to inspect the responses that are being processed in a certain point of your spider, if only to check
that response you expect is getting there.
This can be achieved by using the scrapy.shell.inspect_response function.
Here’s an example of how you would call it from your spider:
import scrapy
class MySpider(scrapy.Spider):
name = "myspider"
start_urls = [
"http://example.com",
"http://example.org",
"http://example.net",
]
inspect_response(response, self)
When you run the spider, you will get something similar to this:
>>> response.url
'http://example.org'
>>> response.xpath('//h1[@class="fn"]')
[]
Nope, it doesn’t. So you can open the response in your web browser and see if it’s the response you were expecting:
>>> view(response)
True
Finally you hit Ctrl-D (or Ctrl-Z in Windows) to exit the shell and resume the crawling:
>>> ^D
2014-01-23 17:50:03-0400 [scrapy] DEBUG: Crawled (200) <GET http://example.net>
˓→(referer: None)
...
Note that you can’t use the fetch shortcut here since the Scrapy engine is blocked by the shell. However, after you
leave the shell, the spider will continue crawling where it stopped, as shown above.
Item Pipeline
After an item has been scraped by a spider, it is sent to the Item Pipeline which processes it through several components
that are executed sequentially.
Each item pipeline component (sometimes referred as just “Item Pipeline”) is a Python class that implements a simple
method. They receive an item and perform an action over it, also deciding if the item should continue through the
pipeline or be dropped and no longer processed.
Typical uses of item pipelines are:
• cleansing HTML data
• validating scraped data (checking that the items contain certain fields)
• checking for duplicates (and dropping them)
• storing the scraped item in a database
Each item pipeline component is a Python class that must implement the following method:
process_item(self, item, spider)
This method is called for every item pipeline component and must either return a dict with data, Item (or any
descendant class) object or raise a DropItem exception. Dropped items are no longer processed by further
pipeline components.
Parameters
• item (Item object or a dict) – the item scraped
• spider (Spider object) – the spider which scraped the item
Additionally, they may also implement the following methods:
open_spider(self, spider)
This method is called when the spider is opened.
Parameters spider (Spider object) – the spider which was opened
close_spider(self, spider)
This method is called when the spider is closed.
Parameters spider (Spider object) – the spider which was closed
from_crawler(cls, crawler)
If present, this classmethod is called to create a pipeline instance from a Crawler. It must return a new instance
of the pipeline. Crawler object provides access to all Scrapy core components like settings and signals; it is a
way for pipeline to access them and hook its functionality into Scrapy.
Parameters crawler (Crawler object) – crawler that uses this pipeline
Let’s take a look at the following hypothetical pipeline that adjusts the price attribute for those items that do not
include VAT (price_excludes_vat attribute), and drops those items which don’t contain a price:
from scrapy.exceptions import DropItem
class PricePipeline(object):
vat_factor = 1.15
The following pipeline stores all scraped items (from all spiders) into a single items.jl file, containing one item
per line serialized in JSON format:
import json
class JsonWriterPipeline(object):
def __init__(self):
self.file = open('items.jl', 'wb')
Note: The purpose of JsonWriterPipeline is just to introduce how to write item pipelines. If you really want to store
all scraped items into a JSON file you should use the Feed exports.
In this example we’ll write items to MongoDB using pymongo. MongoDB address and database name are specified
in Scrapy settings; MongoDB collection is named after item class.
The main point of this example is to show how to use from_crawler() method and how to clean up the resources
properly.
Note: Previous example (JsonWriterPipeline) doesn’t clean up resources properly. Fixing it is left as an exercise for
the reader.
import pymongo
class MongoPipeline(object):
collection_name = 'scrapy_items'
@classmethod
def from_crawler(cls, crawler):
return cls(
mongo_uri=crawler.settings.get('MONGO_URI'),
mongo_db=crawler.settings.get('MONGO_DATABASE', 'items')
)
Duplicates filter
A filter that looks for duplicate items, and drops those items that were already processed. Let’s say that our items have
a unique id, but our spider returns multiples items with the same id:
from scrapy.exceptions import DropItem
class DuplicatesPipeline(object):
def __init__(self):
self.ids_seen = set()
To activate an Item Pipeline component you must add its class to the ITEM_PIPELINES setting, like in the following
example:
ITEM_PIPELINES = {
'myproject.pipelines.PricePipeline': 300,
'myproject.pipelines.JsonWriterPipeline': 800,
}
The integer values you assign to classes in this setting determine the order in which they run: items go through from
lower valued to higher valued classes. It’s customary to define these numbers in the 0-1000 range.
Feed exports
Serialization formats
For serializing the scraped data, the feed exports use the Item exporters. These formats are supported out of the box:
• JSON
• JSON lines
• CSV
• XML
But you can also extend the supported format through the FEED_EXPORTERS setting.
JSON
• FEED_FORMAT: json
• Exporter used: JsonItemExporter
• See this warning if you’re using JSON with large feeds.
JSON lines
• FEED_FORMAT: jsonlines
• Exporter used: JsonLinesItemExporter
CSV
• FEED_FORMAT: csv
• Exporter used: CsvItemExporter
• To specify columns to export and their order use FEED_EXPORT_FIELDS. Other feed exporters can also use
this option, but it is important for CSV because unlike many other export formats CSV uses a fixed header.
XML
• FEED_FORMAT: xml
• Exporter used: XmlItemExporter
Pickle
• FEED_FORMAT: pickle
• Exporter used: PickleItemExporter
Marshal
• FEED_FORMAT: marshal
• Exporter used: MarshalItemExporter
Storages
When using the feed exports you define where to store the feed using a URI (through the FEED_URI setting). The
feed exports supports multiple storage backend types which are defined by the URI scheme.
The storages backends supported out of the box are:
• Local filesystem
• FTP
• S3 (requires boto)
• Standard output
Some storage backends may be unavailable if the required external libraries are not available. For example, the S3
backend is only available if the boto library is installed.
The storage URI can also contain parameters that get replaced when the feed is being created. These parameters are:
• %(time)s - gets replaced by a timestamp when the feed is being created
• %(name)s - gets replaced by the spider name
Any other named parameter gets replaced by the spider attribute of the same name. For example, %(site_id)s
would get replaced by the spider.site_id attribute the moment the feed is being created.
Here are some examples to illustrate:
• Store in FTP using one directory per spider:
– ftp://user:password@ftp.example.com/scraping/feeds/%(name)s/%(time)s.
json
• Store in S3 using one directory per spider:
– s3://mybucket/scraping/feeds/%(name)s/%(time)s.json
Storage backends
Local filesystem
FTP
S3
– s3://aws_key:aws_secret@mybucket/path/to/export.csv
• Required external libraries: boto
The AWS credentials can be passed as user/password in the URI, or they can be passed through the following settings:
• AWS_ACCESS_KEY_ID
• AWS_SECRET_ACCESS_KEY
Standard output
The feeds are written to the standard output of the Scrapy process.
• URI scheme: stdout
• Example URI: stdout:
• Required external libraries: none
Settings
These are the settings used for configuring the feed exports:
• FEED_URI (mandatory)
• FEED_FORMAT
• FEED_STORAGES
• FEED_EXPORTERS
• FEED_STORE_EMPTY
• FEED_EXPORT_FIELDS
FEED_URI
Default: None
The URI of the export feed. See Storage backends for supported URI schemes.
This setting is required for enabling the feed exports.
FEED_FORMAT
The serialization format to be used for the feed. See Serialization formats for possible values.
FEED_EXPORT_FIELDS
Default: None
A list of fields to export, optional. Example: FEED_EXPORT_FIELDS = ["foo", "bar", "baz"].
Use FEED_EXPORT_FIELDS option to define fields to export and their order.
When FEED_EXPORT_FIELDS is empty or None (default), Scrapy uses fields defined in dicts or Item subclasses a
spider is yielding.
If an exporter requires a fixed set of fields (this is the case for CSV export format) and FEED_EXPORT_FIELDS is
empty or None, then Scrapy tries to infer field names from the exported data - currently it uses field names from the
first item.
FEED_STORE_EMPTY
Default: False
Whether to export empty feeds (ie. feeds with no items).
FEED_STORAGES
Default:: {}
A dict containing additional feed storage backends supported by your project. The keys are URI schemes and the
values are paths to storage classes.
FEED_STORAGES_BASE
Default:
{
'': 'scrapy.extensions.feedexport.FileFeedStorage',
'file': 'scrapy.extensions.feedexport.FileFeedStorage',
'stdout': 'scrapy.extensions.feedexport.StdoutFeedStorage',
's3': 'scrapy.extensions.feedexport.S3FeedStorage',
'ftp': 'scrapy.extensions.feedexport.FTPFeedStorage',
}
FEED_EXPORTERS
Default:: {}
A dict containing additional exporters supported by your project. The keys are URI schemes and the values are paths
to Item exporter classes.
FEED_EXPORTERS_BASE
Default:
FEED_EXPORTERS_BASE = {
'json': 'scrapy.exporters.JsonItemExporter',
'jsonlines': 'scrapy.exporters.JsonLinesItemExporter',
'csv': 'scrapy.exporters.CsvItemExporter',
'xml': 'scrapy.exporters.XmlItemExporter',
'marshal': 'scrapy.exporters.MarshalItemExporter',
}
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
request_with_cookies = Request(url="http://www.example.com",
cookies={'currency': 'USD',
˓→'country': 'UY'})
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 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. However, if, for some reason, you want to avoid merging with existing cookies
you can instruct Scrapy to do so by setting the dont_merge_cookies key to True in the
Request.meta.
Example of request without merging cookies:
request_with_cookies = Request(url="http://www.example.com",
cookies={'currency': 'USD', 'country
˓→': 'UY'},
meta={'dont_merge_cookies': True})
replace([url, method, headers, body, cookies, meta, encoding, dont_filter, callback, errback ])
Return a Request object with the same members, except for those members given new values by whichever
keyword arguments are specified. The attribute Request.meta is copied by default (unless a new value
is given in the meta argument). See also 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:
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. You can use the Request.meta attribute for that.
Here’s an example of how to pass an item using this mechanism, to populate different fields from different pages:
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:
• dont_redirect
• dont_retry
• handle_httpstatus_list
• handle_httpstatus_all
• dont_merge_cookies (see cookies parameter of Request constructor)
• cookiejar
• dont_cache
• redirect_urls
• bindaddress
• dont_obey_robotstxt
• download_timeout
• download_maxsize
• proxy
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.
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, ... ])
The FormRequest class adds a new argument to the constructor. 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:
• formname (string) – if given, the form with name attribute set to this value will be
used.
• formxpath (string) – if given, the first form that matches the xpath 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.
• 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 (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 constructor.
New in version 0.10.3: The formname parameter.
New in version 0.17: The formxpath parameter.
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)]
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 scrapy
class LoginSpider(scrapy.Spider):
name = 'example.com'
start_urls = ['http://www.example.com/users/login.php']
Response objects
•This attribute is only available in the spider code, and in the Spider Middlewares, but not in Down-
loader 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 (ie. 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
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.
copy()
Returns a new Response which is a copy of this Response.
replace([url, status, headers, body, request, flags, cls ])
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)
Constructs an absolute url by combining the Response’s url with a possible relative url.
This is a wrapper over urlparse.urljoin, it’s merely an alias for making this call:
urlparse.urljoin(response.url, url)
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
response.body.decode(response.encoding)
unicode(response.body)
Since, in the latter case, you would be using the system default encoding (typically ascii) to convert the
body to unicode, instead of the response encoding.
xpath(query)
A shortcut to TextResponse.selector.xpath(query):
response.xpath('//p')
css(query)
A shortcut to TextResponse.selector.css(query):
response.css('p')
HtmlResponse objects
XmlResponse objects
Link Extractors
Link extractors are objects whose only purpose is to extract links from web pages (scrapy.http.Response
objects) which will be eventually followed.
There is scrapy.linkextractors import LinkExtractor available in Scrapy, but you can create your
own custom Link Extractors to suit your needs by implementing a simple interface.
The only public method that every link extractor has is extract_links, which receives a Response object
and returns a list of scrapy.link.Link objects. Link extractors are meant to be instantiated once and their
extract_links method called several times with different responses to extract links to follow.
Link extractors are used in the CrawlSpider class (available in Scrapy), through a set of rules, but you can also use
it in your spiders, even if you don’t subclass from CrawlSpider, as its purpose is very simple: to extract links.
Link extractors classes bundled with Scrapy are provided in the scrapy.linkextractors module.
The default link extractor is LinkExtractor, which is the same as LxmlLinkExtractor:
There used to be other link extractor classes in previous Scrapy versions, but they are deprecated now.
LxmlLinkExtractor
• restrict_css (str or list) – a CSS selector (or list of selectors) which defines
regions inside the response where links should be extracted from. Has the same behaviour
as restrict_xpaths.
• tags (str or list) – a tag or a list of tags to consider when extracting links. Defaults
to ('a', 'area').
• attrs (list) – an attribute or list of attributes which should be considered when look-
ing for links to extract (only for those tags specified in the tags parameter). Defaults to
('href',)
• canonicalize (boolean) – canonicalize each extracted url (using
scrapy.utils.url.canonicalize_url). Defaults to True.
• unique (boolean) – whether duplicate filtering should be applied to extracted links.
• process_value (callable) – a function which receives each value extracted from the
tag and attributes scanned and can modify the value and return a new one, or return None
to ignore the link altogether. If not given, process_value defaults to lambda x: x.
For example, to extract links from this code:
def process_value(value):
m = re.search("javascript:goToPage\('(.*?)'", value)
if m:
return m.group(1)
Settings
The Scrapy settings allows you to customize the behaviour of all Scrapy components, including the core, extensions,
pipelines and spiders themselves.
The infrastructure of the settings provides a global namespace of key-value mappings that the code can use to pull
configuration values from. The settings can be populated through different mechanisms, which are described below.
The settings are also the mechanism for selecting the currently active Scrapy project (in case you have many).
For a list of available built-in settings see: Built-in settings reference.
When you use Scrapy, you have to tell it which settings you’re using. You can do this by using an environment variable,
SCRAPY_SETTINGS_MODULE.
The value of SCRAPY_SETTINGS_MODULE should be in Python path syntax, e.g. myproject.settings. Note
that the settings module should be on the Python import search path.
Settings can be populated using different mechanisms, each of which having a different precedence. Here is the list of
them in decreasing order of precedence:
Arguments provided by the command line are the ones that take most precedence, overriding any other options. You
can explicitly override one (or more) settings using the -s (or --set) command line option.
Example:
2. Settings per-spider
Spiders (See the Spiders chapter for reference) can define their own settings that will take precedence and override the
project ones. They can do so by setting their scrapy.spiders.Spider.custom_settings attribute.
The project settings module is the standard configuration file for your Scrapy project. It’s where most of your custom
settings will be populated. For example:: myproject.settings.
Each Scrapy tool command can have its own default settings, which override the global default settings. Those custom
command settings are specified in the default_settings attribute of the command class.
The global defaults are located in the scrapy.settings.default_settings module and documented in the
Built-in settings reference section.
Settings can be accessed through the scrapy.crawler.Crawler.settings attribute of the Crawler that is
passed to from_crawler method in extensions and middlewares:
3.11. Settings 85
Scrapy Documentation, Release 1.0.7
class MyExtension(object):
@classmethod
def from_crawler(cls, crawler):
settings = crawler.settings
if settings['LOG_ENABLED']:
print "log is enabled!"
In other words, settings can be accessed like a dict, but it’s usually preferred to extract the setting in the format you
need it to avoid type errors. In order to do that you’ll have to use one of the methods provided the Settings API.
Setting names are usually prefixed with the component that they configure. For example, proper setting names for
a fictional robots.txt extension would be ROBOTSTXT_ENABLED, ROBOTSTXT_OBEY, ROBOTSTXT_CACHEDIR,
etc.
Here’s a list of all available Scrapy settings, in alphabetical order, along with their default values and the scope where
they apply.
The scope, where available, shows where the setting is being used, if it’s tied to any particular component. In that case
the module of that component will be shown, typically an extension, middleware or pipeline. It also means that the
component must be enabled in order for the setting to have any effect.
AWS_ACCESS_KEY_ID
Default: None
The AWS access key used by code that requires access to Amazon Web services, such as the S3 feed storage backend.
AWS_SECRET_ACCESS_KEY
Default: None
The AWS secret key used by code that requires access to Amazon Web services, such as the S3 feed storage backend.
BOT_NAME
Default: 'scrapybot'
The name of the bot implemented by this Scrapy project (also known as the project name). This will be used to
construct the User-Agent by default, and also for logging.
It’s automatically populated with your project name when you create your project with the startproject com-
mand.
CONCURRENT_ITEMS
Default: 100
Maximum number of concurrent items (per response) to process in parallel in the Item Processor (also known as the
Item Pipeline).
CONCURRENT_REQUESTS
Default: 16
The maximum number of concurrent (ie. simultaneous) requests that will be performed by the Scrapy downloader.
CONCURRENT_REQUESTS_PER_DOMAIN
Default: 8
The maximum number of concurrent (ie. simultaneous) requests that will be performed to any single domain.
CONCURRENT_REQUESTS_PER_IP
Default: 0
The maximum number of concurrent (ie. simultaneous) requests that will be performed to any single IP. If non-
zero, the CONCURRENT_REQUESTS_PER_DOMAIN setting is ignored, and this one is used instead. In other words,
concurrency limits will be applied per IP, not per domain.
This setting also affects DOWNLOAD_DELAY: if CONCURRENT_REQUESTS_PER_IP is non-zero, download delay
is enforced per IP, not per domain.
DEFAULT_ITEM_CLASS
Default: 'scrapy.item.Item'
The default class that will be used for instantiating items in the the Scrapy shell.
DEFAULT_REQUEST_HEADERS
Default:
{
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en',
}
The default headers used for Scrapy HTTP Requests. They’re populated in the DefaultHeadersMiddleware.
DEPTH_LIMIT
Default: 0
The maximum depth that will be allowed to crawl for any site. If zero, no limit will be imposed.
3.11. Settings 87
Scrapy Documentation, Release 1.0.7
DEPTH_PRIORITY
Default: 0
An integer that is used to adjust the request priority based on its depth.
If zero, no priority adjustment is made from depth.
DEPTH_STATS
Default: True
Whether to collect maximum depth stats.
DEPTH_STATS_VERBOSE
Default: False
Whether to collect verbose depth stats. If this is enabled, the number of requests for each depth is collected in the
stats.
DNSCACHE_ENABLED
Default: True
Whether to enable DNS in-memory cache.
DNSCACHE_SIZE
Default: 10000
DNS in-memory cache size.
DNS_TIMEOUT
Default: 60
Timeout for processing of DNS queries in seconds. Float is supported.
DOWNLOADER
Default: 'scrapy.core.downloader.Downloader'
The downloader to use for crawling.
DOWNLOADER_MIDDLEWARES
Default:: {}
A dict containing the downloader middlewares enabled in your project, and their orders. For more info see Activating
a downloader middleware.
DOWNLOADER_MIDDLEWARES_BASE
Default:
{
'scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware': 100,
'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware': 300,
'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware': 350,
'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': 400,
'scrapy.downloadermiddlewares.retry.RetryMiddleware': 500,
'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware': 550,
'scrapy.downloadermiddlewares.ajaxcrawl.AjaxCrawlMiddleware': 560,
'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware': 580,
'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 590,
'scrapy.downloadermiddlewares.redirect.RedirectMiddleware': 600,
'scrapy.downloadermiddlewares.cookies.CookiesMiddleware': 700,
'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware': 750,
'scrapy.downloadermiddlewares.chunked.ChunkedTransferMiddleware': 830,
'scrapy.downloadermiddlewares.stats.DownloaderStats': 850,
'scrapy.downloadermiddlewares.httpcache.HttpCacheMiddleware': 900,
}
A dict containing the downloader middlewares enabled by default in Scrapy. You should never modify this setting in
your project, modify DOWNLOADER_MIDDLEWARES instead. For more info see Activating a downloader middle-
ware.
DOWNLOADER_STATS
Default: True
Whether to enable downloader stats collection.
DOWNLOAD_DELAY
Default: 0
The amount of time (in secs) that the downloader should wait before downloading consecutive pages from the same
website. This can be used to throttle the crawling speed to avoid hitting servers too hard. Decimal numbers are
supported. Example:
This setting is also affected by the RANDOMIZE_DOWNLOAD_DELAY setting (which is enabled by default). By
default, Scrapy doesn’t wait a fixed amount of time between requests, but uses a random interval between 0.5 and 1.5
* DOWNLOAD_DELAY.
When CONCURRENT_REQUESTS_PER_IP is non-zero, delays are enforced per ip address instead of per domain.
You can also change this setting per spider by setting download_delay spider attribute.
DOWNLOAD_HANDLERS
Default: {}
A dict containing the request downloader handlers enabled in your project. See DOWNLOAD_HANDLERS_BASE for
example format.
3.11. Settings 89
Scrapy Documentation, Release 1.0.7
DOWNLOAD_HANDLERS_BASE
Default:
{
'file': 'scrapy.core.downloader.handlers.file.FileDownloadHandler',
'http': 'scrapy.core.downloader.handlers.http.HttpDownloadHandler',
'https': 'scrapy.core.downloader.handlers.http.HttpDownloadHandler',
's3': 'scrapy.core.downloader.handlers.s3.S3DownloadHandler',
}
A dict containing the request download handlers enabled by default in Scrapy. You should never modify this setting in
your project, modify DOWNLOAD_HANDLERS instead.
If you want to disable any of the above download handlers you must define them in your project’s
DOWNLOAD_HANDLERS setting and assign None as their value. For example, if you want to disable the file download
handler:
DOWNLOAD_HANDLERS = {
'file': None,
}
DOWNLOAD_TIMEOUT
Default: 180
The amount of time (in secs) that the downloader will wait before timing out.
Note: This timeout can be set per spider using download_timeout spider attribute and per-request using
download_timeout Request.meta key.
DOWNLOAD_MAXSIZE
Note: This size can be set per spider using download_maxsize spider attribute and per-request using
download_maxsize Request.meta key.
This feature needs Twisted >= 11.1.
DOWNLOAD_WARNSIZE
Note: This size can be set per spider using download_warnsize spider attribute and per-request using
download_warnsize Request.meta key.
This feature needs Twisted >= 11.1.
DUPEFILTER_CLASS
Default: 'scrapy.dupefilters.RFPDupeFilter'
The class used to detect and filter duplicate requests.
The default (RFPDupeFilter) filters based on request fingerprint using the scrapy.utils.request.
request_fingerprint function. In order to change the way duplicates are checked you could subclass
RFPDupeFilter and override its request_fingerprint method. This method should accept scrapy
Request object and return its fingerprint (a string).
DUPEFILTER_DEBUG
Default: False
By default, RFPDupeFilter only logs the first duplicate request. Setting DUPEFILTER_DEBUG to True will
make it log all duplicate requests.
EDITOR
EXTENSIONS
Default:: {}
A dict containing the extensions enabled in your project, and their orders.
EXTENSIONS_BASE
Default:
{
'scrapy.extensions.corestats.CoreStats': 0,
'scrapy.telnet.TelnetConsole': 0,
'scrapy.extensions.memusage.MemoryUsage': 0,
'scrapy.extensions.memdebug.MemoryDebugger': 0,
'scrapy.extensions.closespider.CloseSpider': 0,
'scrapy.extensions.feedexport.FeedExporter': 0,
'scrapy.extensions.logstats.LogStats': 0,
'scrapy.extensions.spiderstate.SpiderState': 0,
'scrapy.extensions.throttle.AutoThrottle': 0,
}
3.11. Settings 91
Scrapy Documentation, Release 1.0.7
The list of available extensions. Keep in mind that some of them need to be enabled through a setting. By default, this
setting contains all stable built-in extensions.
For more information See the extensions user guide and the list of available extensions.
ITEM_PIPELINES
Default: {}
A dict containing the item pipelines to use, and their orders. The dict is empty by default order values are arbitrary but
it’s customary to define them in the 0-1000 range.
Lists are supported in ITEM_PIPELINES for backwards compatibility, but they are deprecated.
Example:
ITEM_PIPELINES = {
'mybot.pipelines.validate.ValidateMyItem': 300,
'mybot.pipelines.validate.StoreMyItem': 800,
}
ITEM_PIPELINES_BASE
Default: {}
A dict containing the pipelines enabled by default in Scrapy. You should never modify this setting in your project,
modify ITEM_PIPELINES instead.
LOG_ENABLED
Default: True
Whether to enable logging.
LOG_ENCODING
Default: 'utf-8'
The encoding to use for logging.
LOG_FILE
Default: None
File name to use for logging output. If None, standard error will be used.
LOG_FORMAT
LOG_DATEFORMAT
LOG_LEVEL
Default: 'DEBUG'
Minimum level to log. Available levels are: CRITICAL, ERROR, WARNING, INFO, DEBUG. For more info see
Logging.
LOG_STDOUT
Default: False
If True, all standard output (and error) of your process will be redirected to the log. For example if you print
'hello' it will appear in the Scrapy log.
MEMDEBUG_ENABLED
Default: False
Whether to enable memory debugging.
MEMDEBUG_NOTIFY
Default: []
When memory debugging is enabled a memory report will be sent to the specified addresses if this setting is not empty,
otherwise the report will be written to the log.
Example:
MEMDEBUG_NOTIFY = ['user@example.com']
MEMUSAGE_ENABLED
Default: False
Scope: scrapy.extensions.memusage
Whether to enable the memory usage extension that will shutdown the Scrapy process when it exceeds a memory limit,
and also notify by email when that happened.
See Memory usage extension.
3.11. Settings 93
Scrapy Documentation, Release 1.0.7
MEMUSAGE_LIMIT_MB
Default: 0
Scope: scrapy.extensions.memusage
The maximum amount of memory to allow (in megabytes) before shutting down Scrapy (if MEMUSAGE_ENABLED
is True). If zero, no check will be performed.
See Memory usage extension.
MEMUSAGE_NOTIFY_MAIL
Default: False
Scope: scrapy.extensions.memusage
A list of emails to notify if the memory limit has been reached.
Example:
MEMUSAGE_NOTIFY_MAIL = ['user@example.com']
MEMUSAGE_REPORT
Default: False
Scope: scrapy.extensions.memusage
Whether to send a memory usage report after each spider has been closed.
See Memory usage extension.
MEMUSAGE_WARNING_MB
Default: 0
Scope: scrapy.extensions.memusage
The maximum amount of memory to allow (in megabytes) before sending a warning email notifying about it. If zero,
no warning will be produced.
NEWSPIDER_MODULE
Default: ''
Module where to create new spiders using the genspider command.
Example:
NEWSPIDER_MODULE = 'mybot.spiders_dev'
RANDOMIZE_DOWNLOAD_DELAY
Default: True
If enabled, Scrapy will wait a random amount of time (between 0.5 and 1.5 * DOWNLOAD_DELAY) while fetching
requests from the same website.
This randomization decreases the chance of the crawler being detected (and subsequently blocked) by sites which
analyze requests looking for statistically significant similarities in the time between their requests.
The randomization policy is the same used by wget --random-wait option.
If DOWNLOAD_DELAY is zero (default) this option has no effect.
REACTOR_THREADPOOL_MAXSIZE
Default: 10
The maximum limit for Twisted Reactor thread pool size. This is common multi-purpose thread pool used by various
Scrapy components. Threaded DNS Resolver, BlockingFeedStorage, S3FilesStore just to name a few. Increase this
value if you’re experiencing problems with insufficient blocking IO.
REDIRECT_MAX_TIMES
Default: 20
Defines the maximum times a request can be redirected. After this maximum the request’s response is returned as is.
We used Firefox default value for the same task.
REDIRECT_MAX_METAREFRESH_DELAY
Default: 100
Some sites use meta-refresh for redirecting to a session expired page, so we restrict automatic redirection to a maxi-
mum delay (in seconds)
REDIRECT_PRIORITY_ADJUST
Default: +2
Adjust redirect request priority relative to original request. A negative priority adjust means more priority.
ROBOTSTXT_OBEY
Default: False
Scope: scrapy.downloadermiddlewares.robotstxt
If enabled, Scrapy will respect robots.txt policies. For more information see RobotsTxtMiddleware
SCHEDULER
Default: 'scrapy.core.scheduler.Scheduler'
The scheduler to use for crawling.
3.11. Settings 95
Scrapy Documentation, Release 1.0.7
SPIDER_CONTRACTS
Default:: {}
A dict containing the scrapy contracts enabled in your project, used for testing spiders. For more info see Spiders
Contracts.
SPIDER_CONTRACTS_BASE
Default:
{
'scrapy.contracts.default.UrlContract' : 1,
'scrapy.contracts.default.ReturnsContract': 2,
'scrapy.contracts.default.ScrapesContract': 3,
}
A dict containing the scrapy contracts enabled by default in Scrapy. You should never modify this setting in your
project, modify SPIDER_CONTRACTS instead. For more info see Spiders Contracts.
SPIDER_LOADER_CLASS
Default: 'scrapy.spiderloader.SpiderLoader'
The class that will be used for loading spiders, which must implement the SpiderLoader API.
SPIDER_MIDDLEWARES
Default:: {}
A dict containing the spider middlewares enabled in your project, and their orders. For more info see Activating a
spider middleware.
SPIDER_MIDDLEWARES_BASE
Default:
{
'scrapy.spidermiddlewares.httperror.HttpErrorMiddleware': 50,
'scrapy.spidermiddlewares.offsite.OffsiteMiddleware': 500,
'scrapy.spidermiddlewares.referer.RefererMiddleware': 700,
'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware': 800,
'scrapy.spidermiddlewares.depth.DepthMiddleware': 900,
}
A dict containing the spider middlewares enabled by default in Scrapy. You should never modify this setting in your
project, modify SPIDER_MIDDLEWARES instead. For more info see Activating a spider middleware.
SPIDER_MODULES
Default: []
A list of modules where Scrapy will look for spiders.
Example:
STATS_CLASS
Default: 'scrapy.statscollectors.MemoryStatsCollector'
The class to use for collecting stats, who must implement the Stats Collector API.
STATS_DUMP
Default: True
Dump the Scrapy stats (to the Scrapy log) once the spider finishes.
For more info see: Stats Collection.
STATSMAILER_RCPTS
TELNETCONSOLE_ENABLED
Default: True
A boolean which specifies if the telnet console will be enabled (provided its extension is also enabled).
TELNETCONSOLE_PORT
TEMPLATES_DIR
URLLENGTH_LIMIT
Default: 2083
Scope: spidermiddlewares.urllength
The maximum URL length to allow for crawled URLs. For more information about the default value for this setting
see: http://www.boutell.com/newfaq/misc/urllength.html
3.11. Settings 97
Scrapy Documentation, Release 1.0.7
USER_AGENT
The following settings are documented elsewhere, please check each specific case to see how to enable and use them.
• AJAXCRAWL_ENABLED
• AUTOTHROTTLE_DEBUG
• AUTOTHROTTLE_ENABLED
• AUTOTHROTTLE_MAX_DELAY
• AUTOTHROTTLE_START_DELAY
• AWS_ACCESS_KEY_ID
• AWS_SECRET_ACCESS_KEY
• BOT_NAME
• CLOSESPIDER_ERRORCOUNT
• CLOSESPIDER_ITEMCOUNT
• CLOSESPIDER_PAGECOUNT
• CLOSESPIDER_TIMEOUT
• COMMANDS_MODULE
• COMPRESSION_ENABLED
• CONCURRENT_ITEMS
• CONCURRENT_REQUESTS
• CONCURRENT_REQUESTS_PER_DOMAIN
• CONCURRENT_REQUESTS_PER_IP
• COOKIES_DEBUG
• COOKIES_ENABLED
• DEFAULT_ITEM_CLASS
• DEFAULT_REQUEST_HEADERS
• DEPTH_LIMIT
• DEPTH_PRIORITY
• DEPTH_STATS
• DEPTH_STATS_VERBOSE
• DNSCACHE_ENABLED
• DNSCACHE_SIZE
• DNS_TIMEOUT
• DOWNLOADER
• DOWNLOADER_MIDDLEWARES
• DOWNLOADER_MIDDLEWARES_BASE
• DOWNLOADER_STATS
• DOWNLOAD_DELAY
• DOWNLOAD_HANDLERS
• DOWNLOAD_HANDLERS_BASE
• DOWNLOAD_MAXSIZE
• DOWNLOAD_TIMEOUT
• DOWNLOAD_WARNSIZE
• DUPEFILTER_CLASS
• DUPEFILTER_DEBUG
• EDITOR
• EXTENSIONS
• EXTENSIONS_BASE
• FEED_EXPORTERS
• FEED_EXPORTERS_BASE
• FEED_EXPORT_FIELDS
• FEED_FORMAT
• FEED_STORAGES
• FEED_STORAGES_BASE
• FEED_STORE_EMPTY
• FEED_URI
• FILES_EXPIRES
• FILES_STORE
• HTTPCACHE_DBM_MODULE
• HTTPCACHE_DIR
• HTTPCACHE_ENABLED
• HTTPCACHE_EXPIRATION_SECS
• HTTPCACHE_GZIP
• HTTPCACHE_IGNORE_HTTP_CODES
• HTTPCACHE_IGNORE_MISSING
• HTTPCACHE_IGNORE_SCHEMES
• HTTPCACHE_POLICY
• HTTPCACHE_STORAGE
• HTTPERROR_ALLOWED_CODES
• HTTPERROR_ALLOW_ALL
3.11. Settings 99
Scrapy Documentation, Release 1.0.7
• IMAGES_EXPIRES
• IMAGES_MIN_HEIGHT
• IMAGES_MIN_WIDTH
• IMAGES_STORE
• IMAGES_THUMBS
• ITEM_PIPELINES
• ITEM_PIPELINES_BASE
• LOG_DATEFORMAT
• LOG_ENABLED
• LOG_ENCODING
• LOG_FILE
• LOG_FORMAT
• LOG_LEVEL
• LOG_STDOUT
• MAIL_FROM
• MAIL_HOST
• MAIL_PASS
• MAIL_PORT
• MAIL_SSL
• MAIL_TLS
• MAIL_USER
• MEMDEBUG_ENABLED
• MEMDEBUG_NOTIFY
• MEMUSAGE_ENABLED
• MEMUSAGE_LIMIT_MB
• MEMUSAGE_NOTIFY_MAIL
• MEMUSAGE_REPORT
• MEMUSAGE_WARNING_MB
• METAREFRESH_ENABLED
• NEWSPIDER_MODULE
• RANDOMIZE_DOWNLOAD_DELAY
• REACTOR_THREADPOOL_MAXSIZE
• REDIRECT_ENABLED
• REDIRECT_MAX_METAREFRESH_DELAY
• REDIRECT_MAX_METAREFRESH_DELAY
• REDIRECT_MAX_TIMES
• REDIRECT_MAX_TIMES
• REDIRECT_PRIORITY_ADJUST
• REFERER_ENABLED
• RETRY_ENABLED
• RETRY_HTTP_CODES
• RETRY_TIMES
• ROBOTSTXT_OBEY
• SCHEDULER
• SPIDER_CONTRACTS
• SPIDER_CONTRACTS_BASE
• SPIDER_LOADER_CLASS
• SPIDER_MIDDLEWARES
• SPIDER_MIDDLEWARES_BASE
• SPIDER_MODULES
• STATSMAILER_RCPTS
• STATS_CLASS
• STATS_DUMP
• TELNETCONSOLE_ENABLED
• TELNETCONSOLE_HOST
• TELNETCONSOLE_PORT
• TELNETCONSOLE_PORT
• TEMPLATES_DIR
• URLLENGTH_LIMIT
• USER_AGENT
Exceptions
DropItem
exception scrapy.exceptions.DropItem
The exception that must be raised by item pipeline stages to stop processing an Item. For more information see Item
Pipeline.
CloseSpider
exception scrapy.exceptions.CloseSpider(reason=’cancelled’)
This exception can be raised from a spider callback to request the spider to be closed/stopped. Supported
arguments:
Parameters reason (str) – the reason for closing
For example:
IgnoreRequest
exception scrapy.exceptions.IgnoreRequest
This exception can be raised by the Scheduler or any downloader middleware to indicate that the request should be
ignored.
NotConfigured
exception scrapy.exceptions.NotConfigured
This exception can be raised by some components to indicate that they will remain disabled. Those components
include:
• Extensions
• Item pipelines
• Downloader middlewares
• Spider middlewares
The exception must be raised in the component constructor.
NotSupported
exception scrapy.exceptions.NotSupported
This exception is raised to indicate an unsupported feature.
Command line tool Learn about the command-line tool used to manage your Scrapy project.
Spiders Write the rules to crawl your websites.
Selectors Extract the data from web pages using XPath.
Scrapy shell Test your extraction code in an interactive environment.
Items Define the data you want to scrape.
Item Loaders Populate your items with the extracted data.
Item Pipeline Post-process and store your scraped data.
Feed exports Output your scraped data using different formats and storages.
Requests and Responses Understand the classes used to represent HTTP requests and responses.
Built-in services
Logging
Note: scrapy.log has been deprecated alongside its functions in favor of explicit calls to the Python standard
logging. Keep reading to learn more about the new logging system.
Scrapy uses Python’s builtin logging system for event logging. We’ll provide some simple examples to get you started,
but for more advanced use-cases it’s strongly suggested to read thoroughly its documentation.
Logging works out of the box, and can be configured to some extent with the Scrapy settings listed in Logging settings.
Scrapy calls scrapy.utils.log.configure_logging() to set some reasonable defaults and handle those
settings in Logging settings when running commands, so it’s recommended to manually call it if you’re running Scrapy
from scripts as described in Run Scrapy from a script.
Log levels
Python’s builtin logging defines 5 different levels to indicate severity on a given log message. Here are the standard
ones, listed in decreasing order:
1. logging.CRITICAL - for critical errors (highest severity)
2. logging.ERROR - for regular errors
3. logging.WARNING - for warning messages
4. logging.INFO - for informational messages
5. logging.DEBUG - for debugging messages (lowest severity)
Here’s a quick example of how to log a message using the logging.WARNING level:
105
Scrapy Documentation, Release 1.0.7
import logging
logging.warning("This is a warning")
There are shortcuts for issuing log messages on any of the standard 5 levels, and there’s also a general logging.log
method which takes a given level as argument. If you need so, last example could be rewrote as:
import logging
logging.log(logging.WARNING, "This is a warning")
On top of that, you can create different “loggers” to encapsulate messages (For example, a common practice it’s to
create different loggers for every module). These loggers can be configured independently, and they allow hierarchical
constructions.
Last examples use the root logger behind the scenes, which is a top level logger where all messages are propagated
to (unless otherwise specified). Using logging helpers is merely a shortcut for getting the root logger explicitly, so
this is also an equivalent of last snippets:
import logging
logger = logging.getLogger()
logger.warning("This is a warning")
You can use a different logger just by getting its name with the logging.getLogger function:
import logging
logger = logging.getLogger('mycustomlogger')
logger.warning("This is a warning")
Finally, you can ensure having a custom logger for any module you’re working on by using the __name__ variable,
which is populated with current module’s path:
import logging
logger = logging.getLogger(__name__)
logger.warning("This is a warning")
See also:
Module logging, HowTo Basic Logging Tutorial
Module logging, Loggers Further documentation on loggers
Scrapy provides a logger within each Spider instance, that can be accessed and used like this:
import scrapy
class MySpider(scrapy.Spider):
name = 'myspider'
start_urls = ['http://scrapinghub.com']
That logger is created using the Spider’s name, but you can use any custom Python logger you want. For example:
import logging
import scrapy
logger = logging.getLogger('mycustomlogger')
class MySpider(scrapy.Spider):
name = 'myspider'
start_urls = ['http://scrapinghub.com']
Logging configuration
Loggers on their own don’t manage how messages sent through them are displayed. For this task, different “handlers”
can be attached to any logger instance and they will redirect those messages to appropriate destinations, such as the
standard output, files, emails, etc.
By default, Scrapy sets and configures a handler for the root logger, based on the settings below.
Logging settings
Command-line options
There are command-line arguments, available for all commands, that you can use to override some of the Scrapy
settings regarding logging.
• --logfile FILE Overrides LOG_FILE
scrapy.utils.log module
scrapy.utils.log.configure_logging(settings=None, install_root_handler=True)
Initialize logging defaults for Scrapy.
Parameters
• settings (dict, Settings object or None) – settings used to create and configure a
handler for the root logger (default: None).
• install_root_handler (bool) – whether to install root logging handler (default:
True)
This function does:
•Route warnings and twisted logging through Python standard logging
•Assign DEBUG and ERROR level to Scrapy and Twisted loggers respectively
•Route stdout to log if LOG_STDOUT setting is True
When install_root_handler is True (default), this function also creates a handler for the root logger
according to given settings (see Logging settings). You can override default options using settings argument.
When settings is empty or None, defaults are used.
configure_logging is automatically called when using Scrapy commands, but needs to be called explicitly
when running custom scripts. In that case, its usage is not required but it’s recommended.
If you plan on configuring the handlers yourself is still recommended you call this function, passing in-
stall_root_handler=False. Bear in mind there won’t be any log output set by default in that case.
To get you started on manually configuring logging’s output, you can use logging.basicConfig() to set a basic
root handler. This is an example on how to redirect INFO or higher messages to a file:
import logging
from scrapy.utils.log import configure_logging
configure_logging(install_root_handler=False)
logging.basicConfig(
filename='log.txt',
format='%(levelname)s: %(message)s',
level=logging.INFO
)
Refer to Run Scrapy from a script for more details about using Scrapy this way.
Stats Collection
Scrapy provides a convenient facility for collecting stats in the form of key/values, where values are often counters.
The facility is called the Stats Collector, and can be accessed through the stats attribute of the Crawler API, as
illustrated by the examples in the Common Stats Collector uses section below.
However, the Stats Collector is always available, so you can always import it in your module and use its API (to
increment or set new stat keys), regardless of whether the stats collection is enabled or not. If it’s disabled, the API
will still work but it won’t collect anything. This is aimed at simplifying the stats collector usage: you should spend
no more than one line of code for collecting stats in your spider, Scrapy extension, or whatever code you’re using the
Stats Collector from.
Another feature of the Stats Collector is that it’s very efficient (when enabled) and extremely efficient (almost unno-
ticeable) when disabled.
The Stats Collector keeps a stats table per open spider which is automatically opened when the spider is opened, and
closed when the spider is closed.
Access the stats collector through the stats attribute. Here is an example of an extension that access stats:
class ExtensionThatAccessStats(object):
@classmethod
def from_crawler(cls, crawler):
return cls(crawler.stats)
Besides the basic StatsCollector there are other Stats Collectors available in Scrapy which extend the basic Stats
Collector. You can select which Stats Collector to use through the STATS_CLASS setting. The default Stats Collector
MemoryStatsCollector
class scrapy.statscollectors.MemoryStatsCollector
A simple stats collector that keeps the stats of the last scraping run (for each spider) in memory, after they’re
closed. The stats can be accessed through the spider_stats attribute, which is a dict keyed by spider domain
name.
This is the default Stats Collector used in Scrapy.
spider_stats
A dict of dicts (keyed by spider name) containing the stats of the last scraping run for each spider.
DummyStatsCollector
class scrapy.statscollectors.DummyStatsCollector
A Stats collector which does nothing but is very efficient (because it does nothing). This stats collector can
be set via the STATS_CLASS setting, to disable stats collect in order to improve performance. However, the
performance penalty of stats collection is usually marginal compared to other Scrapy workload like parsing
pages.
Sending e-mail
Although Python makes sending e-mails relatively easy via the smtplib library, Scrapy provides its own facility for
sending e-mails which is very easy to use and it’s implemented using Twisted non-blocking IO, to avoid interfering
with the non-blocking IO of the crawler. It also provides a simple API for sending attachments and it’s very easy to
configure, with a few settings.
Quick example
There are two ways to instantiate the mail sender. You can instantiate it using the standard constructor:
from scrapy.mail import MailSender
mailer = MailSender()
Or you can instantiate it passing a Scrapy settings object, which will respect the settings:
mailer = MailSender.from_settings(settings)
MailSender is the preferred class to use for sending emails from Scrapy, as it uses Twisted non-blocking IO, like the
rest of the framework.
class scrapy.mail.MailSender(smtphost=None, mailfrom=None, smtpuser=None, smtppass=None,
smtpport=None)
Parameters
• smtphost (str) – the SMTP host to use for sending the emails. If omitted, the
MAIL_HOST setting will be used.
• mailfrom (str) – the address used to send emails (in the From: header). If omitted, the
MAIL_FROM setting will be used.
• smtpuser – the SMTP user. If omitted, the MAIL_USER setting will be used. If not given,
no SMTP authentication will be performed.
• smtppass (str) – the SMTP pass for authentication.
• smtpport (int) – the SMTP port to connect to
• smtptls (boolean) – enforce using SMTP STARTTLS
• smtpssl (boolean) – enforce using a secure SSL connection
classmethod from_settings(settings)
Instantiate using a Scrapy settings object, which will respect these Scrapy settings.
Parameters settings (scrapy.settings.Settings object) – the e-mail recipients
send(to, subject, body, cc=None, attachs=(), mimetype=’text/plain’)
Send email to the given recipients.
Parameters
• to (list) – the e-mail recipients
• subject (str) – the subject of the e-mail
• cc (list) – the e-mails to CC
• body (str) – the e-mail body
• attachs (iterable) – an iterable of tuples (attach_name, mimetype,
file_object) where attach_name is a string with the name that will appear on the
e-mail’s attachment, mimetype is the mimetype of the attachment and file_object
is a readable file object with the contents of the attachment
• mimetype (str) – the MIME type of the e-mail
Mail settings
These settings define the default constructor values of the MailSender class, and can be used to configure e-mail
notifications in your project without writing any code (for those extensions and code that uses MailSender).
MAIL_FROM
Default: 'scrapy@localhost'
Sender email to use (From: header) for sending emails.
MAIL_HOST
Default: 'localhost'
SMTP host to use for sending emails.
MAIL_PORT
Default: 25
SMTP port to use for sending emails.
MAIL_USER
Default: None
User to use for SMTP authentication. If disabled no SMTP authentication will be performed.
MAIL_PASS
Default: None
Password to use for SMTP authentication, along with MAIL_USER.
MAIL_TLS
Default: False
Enforce using STARTTLS. STARTTLS is a way to take an existing insecure connection, and upgrade it to a secure
connection using SSL/TLS.
MAIL_SSL
Default: False
Enforce connecting using an SSL encrypted connection
Telnet Console
Scrapy comes with a built-in telnet console for inspecting and controlling a Scrapy running process. The telnet console
is just a regular python shell running inside the Scrapy process, so you can do literally anything from it.
The telnet console is a built-in Scrapy extension which comes enabled by default, but you can also disable it if you
want. For more information about the extension itself see Telnet console extension.
The telnet console listens in the TCP port defined in the TELNETCONSOLE_PORT setting, which defaults to 6023.
To access the console you need to type:
You need the telnet program which comes installed by default in Windows, and most Linux distros.
The telnet console is like a regular Python shell running inside the Scrapy process, so you can do anything from it
including importing new modules, etc.
However, the telnet console comes with some default variables defined for convenience:
Shortcut Description
crawler the Scrapy Crawler (scrapy.crawler.Crawler object)
engine Crawler.engine attribute
spider the active spider
slot the engine slot
extensions the Extension Manager (Crawler.extensions attribute)
stats the Stats Collector (Crawler.stats attribute)
settings the Scrapy settings object (Crawler.settings attribute)
est print a report of the engine status
prefs for memory debugging (see Debugging memory leaks)
p a shortcut to the pprint.pprint function
hpy for memory debugging (see Debugging memory leaks)
Here are some example tasks you can do with the telnet console:
You can use the est() method of the Scrapy engine to quickly show its state using the telnet console:
time()-engine.start_time : 8.62972998619
engine.has_capacity() : False
len(engine.downloader.active) : 16
engine.scraper.is_idle() : False
engine.spider.name : followall
engine.spider_is_idle(engine.spider) : False
engine.slot.closing : False
len(engine.slot.inprogress) : 16
len(engine.slot.scheduler.dqs or []) : 0
len(engine.slot.scheduler.mqs) : 92
len(engine.scraper.slot.queue) : 0
len(engine.scraper.slot.active) : 0
engine.scraper.slot.active_size : 0
engine.scraper.slot.itemproc_size : 0
engine.scraper.slot.needs_backout() : False
To pause:
To resume:
To stop:
scrapy.telnet.update_telnet_vars(telnet_vars)
Sent just before the telnet console is opened. You can hook up to this signal to add, remove or update the
variables that will be available in the telnet local namespace. In order to do that, you need to update the
telnet_vars dict in your handler.
Parameters telnet_vars (dict) – the dict of telnet variables
Telnet settings
These are the settings that control the telnet console’s behaviour:
TELNETCONSOLE_PORT
TELNETCONSOLE_HOST
Default: '127.0.0.1'
The interface the telnet console should listen on
Web Service
BeautifulSoup and lxml are libraries for parsing HTML and XML. Scrapy is an application framework for writing
web spiders that crawl web sites and extract data from them.
Scrapy provides a built-in mechanism for extracting data (called selectors) but you can easily use BeautifulSoup (or
lxml) instead, if you feel more comfortable working with them. After all, they’re just parsing libraries which can be
imported and used from any Python code.
In other words, comparing BeautifulSoup (or lxml) to Scrapy is like comparing jinja2 to Django.
Scrapy is supported under Python 2.7 only. Python 2.6 support was dropped starting at Scrapy 0.20.
No, but there are plans to support Python 3.3+. At the moment, Scrapy works with Python 2.7.
See also:
What Python versions does Scrapy support?.
Probably, but we don’t like that word. We think Django is a great open source project and an example to follow, so
we’ve used it as an inspiration for Scrapy.
117
Scrapy Documentation, Release 1.0.7
We believe that, if something is already done well, there’s no need to reinvent it. This concept, besides being one of
the foundations for open source and free software, not only applies to software but also to documentation, procedures,
policies, etc. So, instead of going through each problem ourselves, we choose to copy ideas from those projects that
have already solved them properly, and focus on the real problems we need to solve.
We’d be proud if Scrapy serves as an inspiration for other projects. Feel free to steal from us!
Yes. Support for HTTP proxies is provided (since Scrapy 0.8) through the HTTP Proxy downloader middleware. See
HttpProxyMiddleware.
By default, Scrapy uses a LIFO queue for storing pending requests, which basically means that it crawls in DFO order.
This order is more convenient in most cases. If you do want to crawl in true BFO order, you can do it by setting the
following settings:
DEPTH_PRIORITY = 1
SCHEDULER_DISK_QUEUE = 'scrapy.squeues.PickleFifoDiskQueue'
SCHEDULER_MEMORY_QUEUE = 'scrapy.squeues.FifoMemoryQueue'
Try changing the default Accept-Language request header by overriding the DEFAULT_REQUEST_HEADERS setting.
See Examples.
Yes. You can use the runspider command. For example, if you have a spider written in a my_spider.py file
you can run it with:
Those messages (logged with DEBUG level) don’t necessarily mean there is a problem, so you may not need to fix
them.
Those messages are thrown by the Offsite Spider Middleware, which is a spider middleware (enabled by default)
whose purpose is to filter out requests to domains outside the ones covered by the spider.
For more info see: OffsiteMiddleware.
It’ll depend on how large your output is. See this warning in JsonItemExporter documentation.
Some signals support returning deferreds from their handlers, others don’t. See the Built-in signals reference to know
which ones.
999 is a custom response status code used by Yahoo sites to throttle requests. Try slowing down the crawling speed
by using a download delay of 2 (or higher) in your spider:
class MySpider(CrawlSpider):
name = 'myspider'
download_delay = 2
Or by setting a global download delay in your project with the DOWNLOAD_DELAY setting.
Yes, but you can also use the Scrapy shell which allows you to quickly analyze (and even modify) the response being
processed by your spider, which is, quite often, more useful than plain old pdb.set_trace().
For more info see Invoking the shell from spiders to inspect responses.
The __VIEWSTATE parameter is used in sites built with ASP.NET/VB.NET. For more info on how it works see this
page. Also, here’s an example spider which scrapes one of these sites.
Parsing big feeds with XPath selectors can be problematic since they need to build the DOM of the entire feed in
memory, and this can be quite slow and consume a lot of memory.
In order to avoid parsing all the entire feed at once in memory, you can use the functions xmliter and csviter
from scrapy.utils.iterators module. In fact, this is what the feed spiders (see Spiders) use under the cover.
Yes, Scrapy receives and keeps track of cookies sent by servers, and sends them back on subsequent requests, like any
regular web browser does.
For more info see Requests and Responses and CookiesMiddleware.
How can I see the cookies being sent and received from Scrapy?
Raise the CloseSpider exception from a callback. For more info see: CloseSpider.
Both spider arguments and settings can be used to configure your spider. There is no strict rule that mandates to use
one or the other, but settings are more suited for parameters that, once set, don’t change much, while spider arguments
are meant to change more often, even on each spider run and sometimes are required for the spider to run at all (for
example, to set the start url of a spider).
To illustrate with an example, assuming you have a spider that needs to log into a site to scrape data, and you only
want to scrape data from a certain section of the site (which varies each time). In that case, the credentials to log in
would be settings, while the url of the section to scrape would be a spider argument.
I’m scraping a XML document and my XPath selector doesn’t return any items
Debugging Spiders
This document explains the most common techniques for debugging spiders. Consider the following scrapy spider
below:
import scrapy
from myproject.items import MyItem
class MySpider(scrapy.Spider):
name = 'myspider'
start_urls = (
'http://example.com/page1',
'http://example.com/page2',
)
Basically this is a simple spider which parses two pages of items (the start_urls). Items also have a details page with
additional information, so we use the meta functionality of Request to pass a partially populated item.
Parse Command
The most basic way of checking the output of your spider is to use the parse command. It allows to check the
behaviour of different parts of the spider at the method level. It has the advantage of being flexible and simple to use,
but does not allow debugging code inside a method.
In order to see the item scraped from a specific url:
# Requests -----------------------------------------------------------------
[]
Using the --verbose or -v option we can see the status at each depth level:
# Requests -----------------------------------------------------------------
[<GET item_details_url>]
# Requests -----------------------------------------------------------------
[]
Checking items scraped from a single start_url, can also be easily achieved using:
Scrapy Shell
While the parse command is very useful for checking behaviour of a spider, it is of little help to check what hap-
pens inside a callback, besides showing the response received and the output. How to debug the situation when
parse_details sometimes receives no item?
Fortunately, the shell is your bread and butter in this case (see Invoking the shell from spiders to inspect responses):
Open in browser
Sometimes you just want to see how a certain response looks in a browser, you can use the open_in_browser
function for that. Here is an example of how you would use it:
open_in_browser will open a browser with the response received by Scrapy at that point, adjusting the base tag
so that images and styles are displayed properly.
Logging
Logging is another useful option for getting information about your spider run. Although not as convenient, it comes
with the advantage that the logs will be available in all future runs should they be necessary again:
Spiders Contracts
Note: This is a new feature (introduced in Scrapy 0.15) and may be subject to minor functionality/API updates.
Check the release notes to be notified of updates.
Testing spiders can get particularly annoying and while nothing prevents you from writing unit tests the task gets
cumbersome quickly. Scrapy offers an integrated way of testing your spiders by the means of contracts.
This allows you to test each callback of your spider by hardcoding a sample url and check various constraints for
how the callback processes the response. Each contract is prefixed with an @ and included in the docstring. See the
following example:
@url http://www.amazon.com/s?field-keywords=selfish+gene
@returns items 1 16
@returns requests 0 0
@scrapes Title Author Year Price
"""
@url url
class scrapy.contracts.default.ReturnsContract
This contract (@returns) sets lower and upper bounds for the items and requests returned by the spider. The
upper bound is optional:
class scrapy.contracts.default.ScrapesContract
This contract (@scrapes) checks that all the items returned by the callback have the specified fields:
Custom Contracts
If you find you need more power than the built-in scrapy contracts you can create and load your own contracts in the
project by using the SPIDER_CONTRACTS setting:
SPIDER_CONTRACTS = {
'myproject.contracts.ResponseCheck': 10,
'myproject.contracts.ItemValidate': 10,
}
Each contract must inherit from scrapy.contracts.Contract and can override three methods:
class scrapy.contracts.Contract(method, *args)
Parameters
class HasHeaderContract(Contract):
""" Demo contract which checks the presence of a custom header
@has_header X-CustomHeader
"""
name = 'has_header'
Common Practices
This section documents common practices when using Scrapy. These are things that cover many topics and don’t often
fall into any other specific section.
You can use the API to run Scrapy from a script, instead of the typical way of running Scrapy via scrapy crawl.
Remember that Scrapy is built on top of the Twisted asynchronous networking library, so you need to run it inside the
Twisted reactor.
First utility you can use to run your spiders is scrapy.crawler.CrawlerProcess. This class will start a
Twisted reactor for you, configuring the logging and setting shutdown handlers. This class is the one used by all
Scrapy commands.
Here’s an example showing how to run a single spider with it.
import scrapy
from scrapy.crawler import CrawlerProcess
class MySpider(scrapy.Spider):
# Your spider definition
...
process = CrawlerProcess({
'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'
})
process.crawl(MySpider)
process.start() # the script will block here until the crawling is finished
Make sure to check CrawlerProcess documentation to get acquainted with its usage details.
If you are inside a Scrapy project there are some additional helpers you can use to import those components
within the project. You can automatically import your spiders passing their name to CrawlerProcess, and use
get_project_settings to get a Settings instance with your project settings.
What follows is a working example of how to do that, using the testspiders project as example.
process = CrawlerProcess(get_project_settings())
There’s another Scrapy utility that provides more control over the crawling process: scrapy.crawler.
CrawlerRunner. This class is a thin wrapper that encapsulates some simple helpers to run multiple crawlers,
but it won’t start or interfere with existing reactors in any way.
Using this class the reactor should be explicitly run after scheduling your spiders. It’s recommended you use
CrawlerRunner instead of CrawlerProcess if your application is already using Twisted and you want to run
Scrapy in the same reactor.
Note that you will also have to shutdown the Twisted reactor yourself after the spider is finished. This can be achieved
by adding callbacks to the deferred returned by the CrawlerRunner.crawl method.
Here’s an example of its usage, along with a callback to manually stop the reactor after MySpider has finished running.
class MySpider(scrapy.Spider):
# Your spider definition
...
d = runner.crawl(MySpider)
d.addBoth(lambda _: reactor.stop())
reactor.run() # the script will block here until the crawling is finished
See also:
Twisted Reactor Overview.
By default, Scrapy runs a single spider per process when you run scrapy crawl. However, Scrapy supports running
multiple spiders per process using the internal API.
Here is an example that runs multiple spiders simultaneously:
import scrapy
from scrapy.crawler import CrawlerProcess
class MySpider1(scrapy.Spider):
# Your first spider definition
...
class MySpider2(scrapy.Spider):
# Your second spider definition
...
process = CrawlerProcess()
process.crawl(MySpider1)
process.crawl(MySpider2)
process.start() # the script will block here until all crawling jobs are finished
class MySpider1(scrapy.Spider):
# Your first spider definition
...
class MySpider2(scrapy.Spider):
# Your second spider definition
...
configure_logging()
runner = CrawlerRunner()
runner.crawl(MySpider1)
runner.crawl(MySpider2)
d = runner.join()
d.addBoth(lambda _: reactor.stop())
reactor.run() # the script will block here until all crawling jobs are finished
Same example but running the spiders sequentially by chaining the deferreds:
from twisted.internet import reactor, defer
from scrapy.crawler import CrawlerRunner
from scrapy.utils.log import configure_logging
class MySpider1(scrapy.Spider):
# Your first spider definition
...
class MySpider2(scrapy.Spider):
# Your second spider definition
...
configure_logging()
runner = CrawlerRunner()
@defer.inlineCallbacks
def crawl():
yield runner.crawl(MySpider1)
yield runner.crawl(MySpider2)
reactor.stop()
crawl()
reactor.run() # the script will block here until the last crawl call is finished
See also:
Run Scrapy from a script.
Distributed crawls
Scrapy doesn’t provide any built-in facility for running crawls in a distribute (multi-server) manner. However, there
are some ways to distribute crawls, which vary depending on how you plan to distribute them.
If you have many spiders, the obvious way to distribute the load is to setup many Scrapyd instances and distribute
spider runs among those.
If you instead want to run a single (big) spider through many machines, what you usually do is partition the urls to
crawl and send them to each separate spider. Here is a concrete example:
First, you prepare the list of urls to crawl and put them into separate files/urls:
http://somedomain.com/urls-to-crawl/spider1/part1.list
http://somedomain.com/urls-to-crawl/spider1/part2.list
http://somedomain.com/urls-to-crawl/spider1/part3.list
Then you fire a spider run on 3 different Scrapyd servers. The spider would receive a (spider) argument part with
the number of the partition to crawl:
Some websites implement certain measures to prevent bots from crawling them, with varying degrees of sophistication.
Getting around those measures can be difficult and tricky, and may sometimes require special infrastructure. Please
consider contacting commercial support if in doubt.
Here are some tips to keep in mind when dealing with these kinds of sites:
• rotate your user agent from a pool of well-known ones from browsers (google around to get a list of them)
• disable cookies (see COOKIES_ENABLED) as some sites may use cookies to spot bot behaviour
Broad Crawls
Scrapy defaults are optimized for crawling specific sites. These sites are often handled by a single Scrapy spider,
although this is not necessary or required (for example, there are generic spiders that handle any given site thrown at
them).
In addition to this “focused crawl”, there is another common type of crawling which covers a large (potentially un-
limited) number of domains, and is only limited by time or other arbitrary constraint, rather than stopping when the
domain was crawled to completion or when there are no more requests to perform. These are called “broad crawls”
and is the typical crawlers employed by search engines.
These are some common properties often found in broad crawls:
• they crawl many domains (often, unbounded) instead of a specific set of sites
• they don’t necessarily crawl domains to completion, because it would impractical (or impossible) to do so, and
instead limit the crawl by time or number of pages crawled
• they are simpler in logic (as opposed to very complex spiders with many extraction rules) because data is often
post-processed in a separate stage
• they crawl many domains concurrently, which allows them to achieve faster crawl speeds by not being limited
by any particular site constraint (each site is crawled slowly to respect politeness, but many sites are crawled in
parallel)
As said above, Scrapy default settings are optimized for focused crawls, not broad crawls. However, due to its asyn-
chronous architecture, Scrapy is very well suited for performing fast broad crawls. This page summarizes some things
you need to keep in mind when using Scrapy for doing broad crawls, along with concrete suggestions of Scrapy
settings to tune in order to achieve an efficient broad crawl.
Increase concurrency
Concurrency is the number of requests that are processed in parallel. There is a global limit and a per-domain limit.
The default global concurrency limit in Scrapy is not suitable for crawling many different domains in parallel, so you
will want to increase it. How much to increase it will depend on how much CPU you crawler will have available. A
good starting point is 100, but the best way to find out is by doing some trials and identifying at what concurrency
your Scrapy process gets CPU bounded. For optimum performance, You should pick a concurrency where CPU usage
is at 80-90%.
To increase the global concurrency use:
CONCURRENT_REQUESTS = 100
Currently Scrapy does DNS resolution in a blocking way with usage of thread pool. With higher concurrency levels
the crawling could be slow or even fail hitting DNS resolver timeouts. Possible solution to increase the number of
threads handling DNS queries. The DNS queue will be processed faster speeding up establishing of connection and
crawling overall.
To increase maximum thread pool size use:
REACTOR_THREADPOOL_MAXSIZE = 20
If you have multiple crawling processes and single central DNS, it can act like DoS attack on the DNS server resulting
to slow down of entire network or even blocking your machines. To avoid this setup your own DNS server with local
cache and upstream to some large DNS like OpenDNS or Verizon.
When doing broad crawls you are often only interested in the crawl rates you get and any errors found. These stats are
reported by Scrapy when using the INFO log level. In order to save CPU (and log storage requirements) you should
not use DEBUG log level when preforming large broad crawls in production. Using DEBUG level when developing
your (broad) crawler may fine though.
To set the log level use:
LOG_LEVEL = 'INFO'
Disable cookies
Disable cookies unless you really need. Cookies are often not needed when doing broad crawls (search engine crawlers
ignore them), and they improve performance by saving some CPU cycles and reducing the memory footprint of your
Scrapy crawler.
To disable cookies use:
COOKIES_ENABLED = False
Disable retries
Retrying failed HTTP requests can slow down the crawls substantially, specially when sites causes are very slow (or
fail) to respond, thus causing a timeout error which gets retried many times, unnecessarily, preventing crawler capacity
to be reused for other domains.
To disable retries use:
RETRY_ENABLED = False
Unless you are crawling from a very slow connection (which shouldn’t be the case for broad crawls) reduce the
download timeout so that stuck requests are discarded quickly and free up capacity to process the next ones.
To reduce the download timeout use:
DOWNLOAD_TIMEOUT = 15
Disable redirects
Consider disabling redirects, unless you are interested in following them. When doing broad crawls it’s common to
save redirects and resolve them when revisiting the site at a later crawl. This also help to keep the number of request
constant per crawl batch, otherwise redirect loops may cause the crawler to dedicate too many resources on any specific
domain.
To disable redirects use:
REDIRECT_ENABLED = False
Some pages (up to 1%, based on empirical data from year 2013) declare themselves as ajax crawlable. This means
they provide plain HTML version of content that is usually available only via AJAX. Pages can indicate it in two ways:
1. by using #! in URL - this is the default way;
2. by using a special meta tag - this way is used on “main”, “index” website pages.
Scrapy handles (1) automatically; to handle (2) enable AjaxCrawlMiddleware:
AJAXCRAWL_ENABLED = True
When doing broad crawls it’s common to crawl a lot of “index” web pages; AjaxCrawlMiddleware helps to crawl
them correctly. It is turned OFF by default because it has some performance overhead, and enabling it for focused
crawls doesn’t make much sense.
Here is a list of tips and advice on using Firefox for scraping, along with a list of useful Firefox add-ons to ease the
scraping process.
Since Firefox add-ons operate on a live browser DOM, what you’ll actually see when inspecting the page source is not
the original HTML, but a modified one after applying some browser clean up and executing Javascript code. Firefox,
in particular, is known for adding <tbody> elements to tables. Scrapy, on the other hand, does not modify the original
page HTML, so you won’t be able to extract any data if you use <tbody in your XPath expressions.
Therefore, you should keep in mind the following things when working with Firefox and XPath:
• Disable Firefox Javascript while inspecting the DOM looking for XPaths to be used in Scrapy
• Never use full XPath paths, use relative and clever ones based on attributes (such as id, class, width, etc)
or any identifying features like contains(@href, 'image').
• Never include <tbody> elements in your XPath expressions unless you really know what you’re doing
Firebug
Firebug is a widely known tool among web developers and it’s also very useful for scraping. In particular, its Inspect
Element feature comes very handy when you need to construct the XPaths for extracting data because it allows you to
view the HTML code of each page element while moving your mouse over it.
See Using Firebug for scraping for a detailed guide on how to use Firebug with Scrapy.
XPather
XPath Checker
XPath Checker is another Firefox add-on for testing XPaths on your pages.
Tamper Data
Tamper Data is a Firefox add-on which allows you to view and modify the HTTP request headers sent by Firefox.
Firebug also allows to view HTTP headers, but not to modify them.
Firecookie
Firecookie makes it easier to view and manage cookies. You can use this extension to create a new cookie, delete
existing cookies, see a list of cookies for the current site, manage cookies permissions and a lot more.
Note: Google Directory, the example website used in this guide is no longer available as it has been shut down by
Google. The concepts in this guide are still valid though. If you want to update this guide to use a new (working) site,
your contribution will be more than welcome!. See Contributing to Scrapy for information on how to do so.
Introduction
This document explains how to use Firebug (a Firefox add-on) to make the scraping process easier and more fun.
For other useful Firefox add-ons see Useful Firefox add-ons for scraping. There are some caveats with using Firefox
add-ons to inspect pages, see Caveats with inspecting the live browser DOM.
In this example, we’ll show how to use Firebug to scrape data from the Google Directory, which contains the same
data as the Open Directory Project used in the tutorial but with a different face.
Firebug comes with a very useful feature called Inspect Element which allows you to inspect the HTML code of the
different page elements just by hovering your mouse over them. Otherwise you would have to search for the tags
manually through the HTML body which can be a very tedious task.
In the following screenshot you can see the Inspect Element tool in action.
At first sight, we can see that the directory is divided in categories, which are also divided in subcategories.
However, it seems that there are more subcategories than the ones being shown in this page, so we’ll keep looking:
As expected, the subcategories contain links to other subcategories, and also links to actual websites, which is the
purpose of the directory.
directory\.google\.com/[A-Z][a-zA-Z_/]+$
So, based on that regular expression we can create the first crawling rule:
Rule(LinkExtractor(allow='directory.google.com/[A-Z][a-zA-Z_/]+$', ),
'parse_category',
follow=True,
),
The Rule object instructs CrawlSpider based spiders how to follow the category links. parse_category will
be a method of the spider which will process and extract data from those pages.
This is how the spider would look so far:
class GoogleDirectorySpider(CrawlSpider):
name = 'directory.google.com'
allowed_domains = ['directory.google.com']
start_urls = ['http://directory.google.com/']
rules = (
Rule(LinkExtractor(allow='directory\.google\.com/[A-Z][a-zA-Z_/]+$'),
'parse_category', follow=True,
),
)
Now we’re going to write the code to extract data from those pages.
With the help of Firebug, we’ll take a look at some page containing links to websites (say http://directory.google.com/
Top/Arts/Awards/) and find out how we can extract those links using Selectors. We’ll also use the Scrapy shell to test
those XPath’s and make sure they work as we expect.
As you can see, the page markup is not very descriptive: the elements don’t contain id, class or any attribute that
clearly identifies them, so we’ll use the ranking bars as a reference point to select the data to extract when we construct
our XPaths.
After using FireBug, we can see that each link is inside a td tag, which is itself inside a tr tag that also contains the
link’s ranking bar (in another td).
So we can select the ranking bar, then find its parent (the tr), and then finally, the link’s td (which contains the data
we want to scrape).
This results in the following XPath:
//td[descendant::a[contains(@href, "#pagerank")]]/following-sibling::td//a
It’s important to use the Scrapy shell to test these complex XPath expressions and make sure they work as expected.
Basically, that expression will look for the ranking bar’s td element, and then select any td element who has a
descendant a element whose href attribute contains the string #pagerank“
Of course, this is not the only XPath, and maybe not the simpler one to select that data. Another approach could be,
for example, to find any font tags that have that grey colour of the links,
Finally, we can write our parse_category() method:
Be aware that you may find some elements which appear in Firebug but not in the original HTML, such as the typical
case of <tbody> elements.
or tags which Therefer in page HTML sources may on Firebug inspects the live DOM
In Scrapy, objects such as Requests, Responses and Items have a finite lifetime: they are created, used for a while, and
finally destroyed.
From all those objects, the Request is probably the one with the longest lifetime, as it stays waiting in the Scheduler
queue until it’s time to process it. For more info see Architecture overview.
As these Scrapy objects have a (rather long) lifetime, there is always the risk of accumulating them in memory without
releasing them properly and thus causing what is known as a “memory leak”.
To help debugging memory leaks, Scrapy provides a built-in mechanism for tracking objects references called trackref ,
and you can also use a third-party library called Guppy for more advanced memory debugging (see below for more
info). Both mechanisms must be used from the Telnet Console.
It happens quite often (sometimes by accident, sometimes on purpose) that the Scrapy developer passes objects refer-
enced in Requests (for example, using the meta attribute or the request callback function) and that effectively bounds
the lifetime of those referenced objects to the lifetime of the Request. This is, by far, the most common cause of
memory leaks in Scrapy projects, and a quite difficult one to debug for newcomers.
In big projects, the spiders are typically written by different people and some of those spiders could be “leaking” and
thus affecting the rest of the other (well-written) spiders when they get to run concurrently, which, in turn, affects the
whole crawling process.
The leak could also come from a custom middleware, pipeline or extension that you have written, if you are not
releasing the (previously allocated) resources properly. For example, allocating resources on spider_opened but
not releasing them on spider_closed may cause problems if you’re running multiple spiders per process.
By default Scrapy keeps the request queue in memory; it includes Request objects and all objects referenced in
Request attributes (e.g. in meta). While not necessarily a leak, this can take a lot of memory. Enabling persistent job
queue could help keeping memory usage in control.
trackref is a module provided by Scrapy to debug the most common cases of memory leaks. It basically tracks the
references to all live Requests, Responses, Item and Selector objects.
You can enter the telnet console and inspect how many objects (of the classes mentioned above) are currently alive
using the prefs() function which is an alias to the print_live_refs() function:
>>> prefs()
Live References
As you can see, that report also shows the “age” of the oldest object in each class. If you’re running multiple spiders
per process chances are you can figure out which spider is leaking by looking at the oldest request or response. You
can get the oldest object of each class using the get_oldest() function (from the telnet console).
The objects tracked by trackrefs are all from these classes (and all its subclasses):
• scrapy.http.Request
• scrapy.http.Response
• scrapy.item.Item
• scrapy.selector.Selector
• scrapy.spiders.Spider
A real example
Let’s see a concrete example of a hypothetical case of memory leaks. Suppose we have some spider with a line similar
to this one:
That line is passing a response reference inside a request which effectively ties the response lifetime to the requests’
one, and that would definitely cause memory leaks.
Let’s see how we can discover the cause (without knowing it a-priori, of course) by using the trackref tool.
After the crawler is running for a few minutes and we notice its memory usage has grown a lot, we can enter its telnet
console and check the live references:
>>> prefs()
Live References
The fact that there are so many live responses (and that they’re so old) is definitely suspicious, as responses should
have a relatively short lifetime compared to Requests. The number of responses is similar to the number of requests,
so it looks like they are tied in a some way. We can now go and check the code of the spider to discover the nasty line
that is generating the leaks (passing response references inside requests).
Sometimes extra information about live objects can be helpful. Let’s check the oldest response:
If you want to iterate over all objects, instead of getting the oldest one, you can use the scrapy.utils.
trackref.iter_all() function:
If your project has too many spiders executed in parallel, the output of prefs() can be difficult to read. For this
reason, that function has a ignore argument which can be used to ignore a particular class (and all its subclases).
For example, this won’t show any live references to spiders:
scrapy.utils.trackref module
scrapy.utils.trackref.print_live_refs(class_name, ignore=NoneType)
Print a report of live references, grouped by class name.
Parameters ignore (class or classes tuple) – if given, all objects from the specified
class (or tuple of classes) will be ignored.
scrapy.utils.trackref.get_oldest(class_name)
Return the oldest object alive with the given class name, or None if none is found. Use print_live_refs()
first to get a list of all tracked live objects per class name.
scrapy.utils.trackref.iter_all(class_name)
Return an iterator over all objects alive with the given class name, or None if none is found. Use
print_live_refs() first to get a list of all tracked live objects per class name.
trackref provides a very convenient mechanism for tracking down memory leaks, but it only keeps track of the
objects that are more likely to cause memory leaks (Requests, Responses, Items, and Selectors). However, there are
other cases where the memory leaks could come from other (more or less obscure) objects. If this is your case, and
you can’t find your leaks using trackref, you still have another resource: the Guppy library.
If you use pip, you can install Guppy with the following command:
pip install guppy
The telnet console also comes with a built-in shortcut (hpy) for accessing Guppy heap objects. Here’s an example to
view all Python objects available in the heap using Guppy:
>>> x = hpy.heap()
>>> x.bytype
Partition of a set of 297033 objects. Total size = 52587824 bytes.
Index Count % Size % Cumulative % Type
0 22307 8 16423880 31 16423880 31 dict
1 122285 41 12441544 24 28865424 55 str
2 68346 23 5966696 11 34832120 66 tuple
3 227 0 5836528 11 40668648 77 unicode
4 2461 1 2222272 4 42890920 82 type
5 16870 6 2024400 4 44915320 85 function
6 13949 5 1673880 3 46589200 89 types.CodeType
7 13422 5 1653104 3 48242304 92 list
8 3735 1 1173680 2 49415984 94 _sre.SRE_Pattern
9 1209 0 456936 1 49872920 95 scrapy.http.headers.Headers
<1676 more rows. Type e.g. '_.more' to view.>
You can see that most space is used by dicts. Then, if you want to see from which attribute those dicts are referenced,
you could do:
>>> x.bytype[0].byvia
Partition of a set of 22307 objects. Total size = 16423880 bytes.
Index Count % Size % Cumulative % Referred Via:
0 10982 49 9416336 57 9416336 57 '.__dict__'
1 1820 8 2681504 16 12097840 74 '.__dict__', '.func_globals'
2 3097 14 1122904 7 13220744 80
3 990 4 277200 2 13497944 82 "['cookies']"
4 987 4 276360 2 13774304 84 "['cache']"
5 985 4 275800 2 14050104 86 "['meta']"
6 897 4 251160 2 14301264 87 '[2]'
7 1 0 196888 1 14498152 88 "['moduleDict']", "['modules']"
As you can see, the Guppy module is very powerful but also requires some deep knowledge about Python internals.
For more info about Guppy, refer to the Guppy documentation.
Sometimes, you may notice that the memory usage of your Scrapy process will only increase, but never decrease.
Unfortunately, this could happen even though neither Scrapy nor your project are leaking memory. This is due to a
(not so well) known problem of Python, which may not return released memory to the operating system in some cases.
For more information on this issue see:
• Python Memory Management
• Python Memory Management Part 2
• Python Memory Management Part 3
The improvements proposed by Evan Jones, which are detailed in this paper, got merged in Python 2.5, but this only
reduces the problem, it doesn’t fix it completely. To quote the paper:
Unfortunately, this patch can only free an arena if there are no more objects allocated in it anymore. This
means that fragmentation is a large issue. An application could have many megabytes of free memory,
scattered throughout all the arenas, but it will be unable to free any of it. This is a problem experienced
by all memory allocators. The only way to solve it is to move to a compacting garbage collector, which is
able to move objects in memory. This would require significant changes to the Python interpreter.
To keep memory consumption reasonable you can split the job into several smaller jobs or enable persistent job queue
and stop/start spider from time to time.
Scrapy provides reusable item pipelines for downloading files attached to a particular item (for example, when you
scrape products and also want to download their images locally). These pipelines share a bit of functionality and
structure (we refer to them as media pipelines), but typically you’ll either use the Files Pipeline or the Images Pipeline.
Both pipelines implement these features:
• Avoid re-downloading media that was downloaded recently
• Specifying where to store the media (filesystem directory, Amazon S3 bucket)
The Images Pipeline has a few extra functions for processing images:
• Convert all downloaded images to a common format (JPG) and mode (RGB)
• Thumbnail generation
• Check images width/height to make sure they meet a minimum constraint
The pipelines also keep an internal queue of those media URLs which are currently being scheduled for download,
and connect those responses that arrive containing the same media to that queue. This avoids downloading the same
media more than once when it’s shared by several items.
The typical workflow, when using the FilesPipeline goes like this:
1. In a Spider, you scrape an item and put the URLs of the desired into a file_urls field.
2. The item is returned from the spider and goes to the item pipeline.
3. When the item reaches the FilesPipeline, the URLs in the file_urls field are scheduled for download
using the standard Scrapy scheduler and downloader (which means the scheduler and downloader middlewares
are reused), but with a higher priority, processing them before other pages are scraped. The item remains
“locked” at that particular pipeline stage until the files have finish downloading (or fail for some reason).
4. When the files are downloaded, another field (files) will be populated with the results. This field will contain
a list of dicts with information about the downloaded files, such as the downloaded path, the original scraped url
(taken from the file_urls field) , and the file checksum. The files in the list of the files field will retain
the same order of the original file_urls field. If some file failed downloading, an error will be logged and
the file won’t be present in the files field.
Using the ImagesPipeline is a lot like using the FilesPipeline, except the default field names used are dif-
ferent: you use image_urls for the image URLs of an item and it will populate an images field for the information
about the downloaded images.
The advantage of using the ImagesPipeline for image files is that you can configure some extra functions like
generating thumbnails and filtering the images based on their size.
The Images Pipeline uses Pillow for thumbnailing and normalizing images to JPEG/RGB format, so you need to install
this library in order to use it. Python Imaging Library (PIL) should also work in most cases, but it is known to cause
troubles in some setups, so we recommend to use Pillow instead of PIL.
Usage example
import scrapy
class MyItem(scrapy.Item):
If you need something more complex and want to override the custom pipeline behaviour, see Extending the Media
Pipelines.
To enable your media pipeline you must first add it to your project ITEM_PIPELINES setting.
For Images Pipeline, use:
ITEM_PIPELINES = {'scrapy.pipelines.images.ImagesPipeline': 1}
ITEM_PIPELINES = {'scrapy.pipelines.files.FilesPipeline': 1}
Note: You can also use both the Files and Images Pipeline at the same time.
Then, configure the target storage setting to a valid value that will be used for storing the downloaded images. Other-
wise the pipeline will remain disabled, even if you include it in the ITEM_PIPELINES setting.
For the Files Pipeline, set the FILES_STORE setting:
FILES_STORE = '/path/to/valid/dir'
IMAGES_STORE = '/path/to/valid/dir'
Supported Storage
File system is currently the only officially supported storage, but there is also (undocumented) support for storing files
in Amazon S3.
The files are stored using a SHA1 hash of their URLs for the file names.
For example, the following image URL:
http://www.example.com/image.jpg
3afec3b4765f8f0a07b78f98c07b83f013567a0a
<IMAGES_STORE>/full/3afec3b4765f8f0a07b78f98c07b83f013567a0a.jpg
Where:
• <IMAGES_STORE> is the directory defined in IMAGES_STORE setting for the Images Pipeline.
• full is a sub-directory to separate full images from thumbnails (if used). For more info see Thumbnail gener-
ation for images.
Additional features
File expiration
The Image Pipeline avoids downloading files that were downloaded recently. To adjust this retention delay use the
FILES_EXPIRES setting (or IMAGES_EXPIRES, in case of Images Pipeline), which specifies the delay in number
of days:
The Images Pipeline can automatically create thumbnails of the downloaded images. In order use this feature,
you must set IMAGES_THUMBS to a dictionary where the keys are the thumbnail names and the values are their
dimensions.
For example:
IMAGES_THUMBS = {
'small': (50, 50),
'big': (270, 270),
}
When you use this feature, the Images Pipeline will create thumbnails of the each specified size with this format:
<IMAGES_STORE>/thumbs/<size_name>/<image_id>.jpg
Where:
• <size_name> is the one specified in the IMAGES_THUMBS dictionary keys (small, big, etc)
• <image_id> is the SHA1 hash of the image url
Example of image files stored using small and big thumbnail names:
<IMAGES_STORE>/full/63bbfea82b8880ed33cdb762aa11fab722a90a24.jpg
<IMAGES_STORE>/thumbs/small/63bbfea82b8880ed33cdb762aa11fab722a90a24.jpg
<IMAGES_STORE>/thumbs/big/63bbfea82b8880ed33cdb762aa11fab722a90a24.jpg
The first one is the full image, as downloaded from the site.
When using the Images Pipeline, you can drop images which are too small, by specifying the minimum allowed size
in the IMAGES_MIN_HEIGHT and IMAGES_MIN_WIDTH settings.
For example:
IMAGES_MIN_HEIGHT = 110
IMAGES_MIN_WIDTH = 110
See here the methods that you can override in your custom Files Pipeline:
class scrapy.pipelines.files.FilesPipeline
get_media_requests(item, info)
As seen on the workflow, the pipeline will get the URLs of the images to download from the item. In order
to do this, you can override the get_media_requests() method and return a Request for each file
URL:
Those requests will be processed by the pipeline and, when they have finished downloading, the results
will be sent to the item_completed() method, as a list of 2-element tuples. Each tuple will contain
(success, file_info_or_error) where:
•success is a boolean which is True if the image was downloaded successfully or False if it failed
for some reason
•file_info_or_error is a dict containing the following keys (if success is True) or a Twisted
Failure if there was a problem.
–url - the url where the file was downloaded from. This is the url of the request returned from the
get_media_requests() method.
–path - the path (relative to FILES_STORE) where the file was stored
–checksum - a MD5 hash of the image contents
The list of tuples received by item_completed() is guaranteed to retain the same order of the requests
returned from the get_media_requests() method.
Here’s a typical value of the results argument:
[(True,
{'checksum': '2b00042f7481c7b056c4b410d28f33cf',
'path': 'full/0a79c461a4062ac383dc4fade7bc09f1384a3910.jpg',
'url': 'http://www.example.com/files/product1.pdf'}),
(False,
Failure(...))]
By default the get_media_requests() method returns None which means there are no files to down-
load for the item.
item_completed(results, items, info)
The FilesPipeline.item_completed() method called when all file requests for a single item
have completed (either finished downloading, or failed for some reason).
The item_completed() method must return the output that will be sent to subsequent item pipeline
stages, so you must return (or drop) the item, as you would in any pipeline.
Here is an example of the item_completed() method where we store the downloaded file paths
(passed in results) in the file_paths item field, and we drop the item if it doesn’t contain any files:
Here is a full example of the Images Pipeline whose methods are examplified above:
import scrapy
from scrapy.pipelines.images import ImagesPipeline
from scrapy.exceptions import DropItem
class MyImagesPipeline(ImagesPipeline):
Ubuntu packages
Warning: python-scrapy is a different package provided by official debian repositories, it’s very outdated and it
isn’t supported by Scrapy team.
Deploying Spiders
This section describes the different options you have for deploying your Scrapy spiders to run them on a regular basis.
Running Scrapy spiders in your local machine is very convenient for the (early) development stage, but not so much
when you need to execute long-running spiders or move spiders to run in production continuously. This is where the
solutions for deploying Scrapy spiders come in.
Popular choices for deploying Scrapy spiders are:
• Scrapyd (open source)
• Scrapy Cloud (cloud-based)
Scrapyd is an open source application to run Scrapy spiders. It provides a server with HTTP API, capable of running
and monitoring Scrapy spiders.
To deploy spiders to Scrapyd, you can use the scrapyd-deploy tool provided by the scrapyd-client package. Please
refer to the scrapyd-deploy documentation for more information.
Scrapyd is maintained by some of the Scrapy developers.
Scrapy Cloud is a hosted, cloud-based service by Scrapinghub, the company behind Scrapy.
Scrapy Cloud removes the need to setup and monitor servers and provides a nice UI to manage spiders and review
scraped items, logs and stats.
To deploy spiders to Scrapy Cloud you can use the shub command line tool. Please refer to the Scrapy Cloud docu-
mentation for more information.
Scrapy Cloud is compatible with Scrapyd and one can switch between them as needed - the configuration is read from
the scrapy.cfg file just like scrapyd-deploy.
AutoThrottle extension
This is an extension for automatically throttling crawling speed based on load of both the Scrapy server and the website
you are crawling.
Design goals
How it works
In Scrapy, the download latency is measured as the time elapsed between establishing the TCP connection and receiv-
ing the HTTP headers.
Note that these latencies are very hard to measure accurately in a cooperative multitasking environment because Scrapy
may be busy processing a spider callback, for example, and unable to attend downloads. However, these latencies
should still give a reasonable estimate of how busy Scrapy (and ultimately, the server) is, and this extension builds on
that premise.
Throttling algorithm
This adjusts download delays and concurrency based on the following rules:
1. spiders always start with one concurrent request and a download delay of AUTOTHROTTLE_START_DELAY
2. when a response is received, the download delay is adjusted to the average of previous download delay and the
latency of the response.
Note: The AutoThrottle extension honours the standard Scrapy settings for concurrency and delay. This
means that it will never set a download delay lower than DOWNLOAD_DELAY or a concurrency higher than
CONCURRENT_REQUESTS_PER_DOMAIN (or CONCURRENT_REQUESTS_PER_IP, depending on which one
you use).
Settings
• CONCURRENT_REQUESTS_PER_DOMAIN
• CONCURRENT_REQUESTS_PER_IP
• DOWNLOAD_DELAY
For more information see Throttling algorithm.
AUTOTHROTTLE_ENABLED
Default: False
Enables the AutoThrottle extension.
AUTOTHROTTLE_START_DELAY
Default: 5.0
The initial download delay (in seconds).
AUTOTHROTTLE_MAX_DELAY
Default: 60.0
The maximum download delay (in seconds) to be set in case of high latencies.
AUTOTHROTTLE_DEBUG
Default: False
Enable AutoThrottle debug mode which will display stats on every response received, so you can see how the throttling
parameters are being adjusted in real time.
Benchmarking
scrapy bench
2013-05-16 13:08:48-0300 [scrapy] INFO: Crawled 74 pages (at 4440 pages/min), scraped
˓→0 items (at 0 items/min)
2013-05-16 13:08:49-0300 [scrapy] INFO: Crawled 143 pages (at 4140 pages/min),
˓→scraped 0 items (at 0 items/min)
2013-05-16 13:08:50-0300 [scrapy] INFO: Crawled 210 pages (at 4020 pages/min),
˓→scraped 0 items (at 0 items/min)
2013-05-16 13:08:51-0300 [scrapy] INFO: Crawled 274 pages (at 3840 pages/min),
˓→scraped 0 items (at 0 items/min)
2013-05-16 13:08:52-0300 [scrapy] INFO: Crawled 343 pages (at 4140 pages/min),
˓→scraped 0 items (at 0 items/min)
2013-05-16 13:08:53-0300 [scrapy] INFO: Crawled 410 pages (at 4020 pages/min),
˓→scraped 0 items (at 0 items/min)
2013-05-16 13:08:54-0300 [scrapy] INFO: Crawled 474 pages (at 3840 pages/min),
˓→scraped 0 items (at 0 items/min)
2013-05-16 13:08:55-0300 [scrapy] INFO: Crawled 538 pages (at 3840 pages/min),
˓→scraped 0 items (at 0 items/min)
2013-05-16 13:08:56-0300 [scrapy] INFO: Crawled 602 pages (at 3840 pages/min),
˓→scraped 0 items (at 0 items/min)
That tells you that Scrapy is able to crawl about 3900 pages per minute in the hardware where you run it. Note that
this is a very simple spider intended to follow links, any custom spider you write will probably do more stuff which
results in slower crawl rates. How slower depends on how much your spider does and how well it’s written.
In the future, more cases will be added to the benchmarking suite to cover other common scenarios.
Sometimes, for big sites, it’s desirable to pause crawls and be able to resume them later.
Scrapy supports this functionality out of the box by providing the following facilities:
• a scheduler that persists scheduled requests on disk
• a duplicates filter that persists visited requests on disk
• an extension that keeps some spider state (key/value pairs) persistent between batches
Job directory
To enable persistence support you just need to define a job directory through the JOBDIR setting. This directory
will be for storing all required data to keep the state of a single job (ie. a spider run). It’s important to note that this
directory must not be shared by different spiders, or even different jobs/runs of the same spider, as it’s meant to be
used for storing the state of a single job.
How to use it
Then, you can stop the spider safely at any time (by pressing Ctrl-C or sending a signal), and resume it later by issuing
the same command:
scrapy crawl somespider -s JOBDIR=crawls/somespider-1
Sometimes you’ll want to keep some persistent spider state between pause/resume batches. You can use the spider.
state attribute for that, which should be a dict. There’s a built-in extension that takes care of serializing, storing and
loading that attribute from the job directory, when the spider starts and stops.
Here’s an example of a callback that uses the spider state (other spider code is omitted for brevity):
def parse_item(self, response):
# parse item here
self.state['items_count'] = self.state.get('items_count', 0) + 1
Persistence gotchas
There are a few things to keep in mind if you want to be able to use the Scrapy persistence support:
Cookies expiration
Cookies may expire. So, if you don’t resume your spider quickly the requests scheduled may no longer work. This
won’t be an issue if you spider doesn’t rely on cookies.
Request serialization
Requests must be serializable by the pickle module, in order for persistence to work, so you should make sure that
your requests are serializable.
The most common issue here is to use lambda functions on request callbacks that can’t be persisted.
So, for example, this won’t work:
def some_callback(self, response):
somearg = 'test'
return scrapy.Request('http://www.example.com', callback=lambda r: self.other_
˓→callback(r, somearg))
Extending Scrapy
Architecture overview
This document describes the architecture of Scrapy and how its components interact.
Overview
The following diagram shows an overview of the Scrapy architecture with its components and an outline of the data
flow that takes place inside the system (shown by the green arrows). A brief description of the components is included
below with links for more detailed information about them. The data flow is also described below.
153
Scrapy Documentation, Release 1.0.7
Components
Scrapy Engine
The engine is responsible for controlling the data flow between all components of the system, and triggering events
when certain actions occur. See the Data Flow section below for more details.
Scheduler
The Scheduler receives requests from the engine and enqueues them for feeding them later (also to the engine) when
the engine requests them.
Downloader
The Downloader is responsible for fetching web pages and feeding them to the engine which, in turn, feeds them to
the spiders.
Spiders
Spiders are custom classes written by Scrapy users to parse responses and extract items (aka scraped items) from them
or additional URLs (requests) to follow. Each spider is able to handle a specific domain (or group of domains). For
more information see Spiders.
Item Pipeline
The Item Pipeline is responsible for processing the items once they have been extracted (or scraped) by the spiders.
Typical tasks include cleansing, validation and persistence (like storing the item in a database). For more information
see Item Pipeline.
Downloader middlewares
Downloader middlewares are specific hooks that sit between the Engine and the Downloader and process requests
when they pass from the Engine to the Downloader, and responses that pass from Downloader to the Engine. They
provide a convenient mechanism for extending Scrapy functionality by plugging custom code. For more information
see Downloader Middleware.
Spider middlewares
Spider middlewares are specific hooks that sit between the Engine and the Spiders and are able to process spider input
(responses) and output (items and requests). They provide a convenient mechanism for extending Scrapy functionality
by plugging custom code. For more information see Spider Middleware.
Data flow
The data flow in Scrapy is controlled by the execution engine, and goes like this:
1. The Engine opens a domain, locates the Spider that handles that domain, and asks the spider for the first URLs
to crawl.
2. The Engine gets the first URLs to crawl from the Spider and schedules them in the Scheduler, as Requests.
3. The Engine asks the Scheduler for the next URLs to crawl.
4. The Scheduler returns the next URLs to crawl to the Engine and the Engine sends them to the Downloader,
passing through the Downloader Middleware (request direction).
5. Once the page finishes downloading the Downloader generates a Response (with that page) and sends it to the
Engine, passing through the Downloader Middleware (response direction).
6. The Engine receives the Response from the Downloader and sends it to the Spider for processing, passing
through the Spider Middleware (input direction).
7. The Spider processes the Response and returns scraped items and new Requests (to follow) to the Engine.
8. The Engine sends scraped items (returned by the Spider) to the Item Pipeline and Requests (returned by spider)
to the Scheduler
9. The process repeats (from step 2) until there are no more requests from the Scheduler, and the Engine closes the
domain.
Event-driven networking
Scrapy is written with Twisted, a popular event-driven networking framework for Python. Thus, it’s implemented
using a non-blocking (aka asynchronous) code for concurrency.
For more information about asynchronous programming and Twisted see these links:
• Introduction to Deferreds in Twisted
• Twisted - hello, asynchronous programming
• Twisted Introduction - Krondo
Downloader Middleware
The downloader middleware is a framework of hooks into Scrapy’s request/response processing. It’s a light, low-level
system for globally altering Scrapy’s requests and responses.
DOWNLOADER_MIDDLEWARES = {
'myproject.middlewares.CustomDownloaderMiddleware': 543,
}
DOWNLOADER_MIDDLEWARES = {
'myproject.middlewares.CustomDownloaderMiddleware': 543,
'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': None,
}
Finally, keep in mind that some middlewares may need to be enabled through a particular setting. See each middleware
documentation for more info.
Each middleware component is a Python class that defines one or more of the following methods:
class scrapy.downloadermiddlewares.DownloaderMiddleware
process_request(request, spider)
This method is called for each request that goes through the download middleware.
process_request() should either: return None, return a Response object, return a Request
object, or raise IgnoreRequest.
If it returns None, Scrapy will continue processing this request, executing all other middlewares until,
finally, the appropriate downloader handler is called the request performed (and its response downloaded).
If it returns a Response object, Scrapy won’t bother calling any other process_request() or
process_exception() methods, or the appropriate download function; it’ll return that response.
The process_response() methods of installed middleware is always called on every response.
If it returns a Request object, Scrapy will stop calling process_request methods and reschedule the
returned request. Once the newly returned request is performed, the appropriate middleware chain will be
called on the downloaded response.
If it raises an IgnoreRequest exception, the process_exception() methods of installed down-
loader middleware will be called. If none of them handle the exception, the errback function of the request
(Request.errback) is called. If no code handles the raised exception, it is ignored and not logged
(unlike other exceptions).
Parameters
• request (Request object) – the request being processed
• spider (Spider object) – the spider for which this request is intended
process_response(request, response, spider)
process_response() should either: return a Response object, return a Request object or raise a
IgnoreRequest exception.
If it returns a Response (it could be the same given response, or a brand-new one), that response will
continue to be processed with the process_response() of the next middleware in the chain.
If it returns a Request object, the middleware chain is halted and the returned request is resched-
uled to be downloaded in the future. This is the same behavior as if a request is returned from
process_request().
If it raises an IgnoreRequest exception, the errback function of the request (Request.errback) is
called. If no code handles the raised exception, it is ignored and not logged (unlike other exceptions).
Parameters
• request (is a Request object) – the request that originated the response
• response (Response object) – the response being processed
• spider (Spider object) – the spider for which this response is intended
process_exception(request, exception, spider)
Scrapy calls process_exception() when a download handler or a process_request() (from a
downloader middleware) raises an exception (including an IgnoreRequest exception)
process_exception() should return: either None, a Response object, or a Request object.
If it returns None, Scrapy will continue processing this exception, executing any other
process_exception() methods of installed middleware, until no middleware is left and the default
exception handling kicks in.
If it returns a Response object, the process_response() method chain of installed middleware is
started, and Scrapy won’t bother calling any other process_exception() methods of middleware.
If it returns a Request object, the returned request is rescheduled to be downloaded in the future. This
stops the execution of process_exception() methods of the middleware the same as returning a
response would.
Parameters
• request (is a Request object) – the request that generated the exception
• exception (an Exception object) – the raised exception
• spider (Spider object) – the spider for which this request is intended
This page describes all downloader middleware components that come with Scrapy. For information on how to use
them and how to write your own downloader middleware, see the downloader middleware usage guide.
For a list of the components enabled by default (and their orders) see the DOWNLOADER_MIDDLEWARES_BASE
setting.
CookiesMiddleware
class scrapy.downloadermiddlewares.cookies.CookiesMiddleware
This middleware enables working with sites that require cookies, such as those that use sessions. It keeps track
of cookies sent by web servers, and send them back on subsequent requests (from that spider), just like web
browsers do.
The following settings can be used to configure the cookie middleware:
• COOKIES_ENABLED
• COOKIES_DEBUG
Keep in mind that the cookiejar meta key is not “sticky”. You need to keep passing it along on subsequent requests.
For example:
COOKIES_ENABLED
Default: True
Whether to enable the cookies middleware. If disabled, no cookies will be sent to web servers.
COOKIES_DEBUG
Default: False
If enabled, Scrapy will log all cookies sent in requests (ie. Cookie header) and all cookies received in responses (ie.
Set-Cookie header).
Here’s an example of a log with COOKIES_DEBUG enabled:
Cookie: clientlanguage_nl=en_EN
2011-04-06 14:35:14-0300 [scrapy] DEBUG: Received cookies from: <200 http://www.
˓→diningcity.com/netherlands/index.html>
[...]
DefaultHeadersMiddleware
class scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware
This middleware sets all default requests headers specified in the DEFAULT_REQUEST_HEADERS setting.
DownloadTimeoutMiddleware
class scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware
This middleware sets the download timeout for requests specified in the DOWNLOAD_TIMEOUT setting or
download_timeout spider attribute.
Note: You can also set download timeout per-request using download_timeout Request.meta key; this is sup-
ported even when DownloadTimeoutMiddleware is disabled.
HttpAuthMiddleware
class scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware
This middleware authenticates all requests generated from certain spiders using Basic access authentication
(aka. HTTP auth).
To enable HTTP authentication from certain spiders, set the http_user and http_pass attributes of those
spiders.
Example:
class SomeIntranetSiteSpider(CrawlSpider):
http_user = 'someuser'
http_pass = 'somepass'
name = 'intranet.example.com'
HttpCacheMiddleware
class scrapy.downloadermiddlewares.httpcache.HttpCacheMiddleware
This middleware provides low-level cache to all HTTP requests and responses. It has to be combined with a
cache storage backend as well as a cache policy.
Scrapy ships with two HTTP cache storage backends:
•Filesystem storage backend (default)
•DBM storage backend
You can change the HTTP cache storage backend with the HTTPCACHE_STORAGE setting. Or you can also
implement your own storage backend.
Scrapy ships with two HTTP cache policies:
•RFC2616 policy
•Dummy policy (default)
You can change the HTTP cache policy with the HTTPCACHE_POLICY setting. Or you can also implement
your own policy. You can also avoid caching a response on every policy using dont_cache meta key equals
True.
This policy has no awareness of any HTTP Cache-Control directives. Every request and its corresponding response are
cached. When the same request is seen again, the response is returned without transferring anything from the Internet.
The Dummy policy is useful for testing spiders faster (without having to wait for downloads every time) and for trying
your spider offline, when an Internet connection is not available. The goal is to be able to “replay” a spider run exactly
as it ran before.
In order to use this policy, set:
• HTTPCACHE_POLICY to scrapy.extensions.httpcache.DummyPolicy
RFC2616 policy
This policy provides a RFC2616 compliant HTTP cache, i.e. with HTTP Cache-Control awareness, aimed at produc-
tion and used in continuous runs to avoid downloading unmodified data (to save bandwidth and speed up crawls).
what is implemented:
• Do not attempt to store responses/requests with no-store cache-control directive set
• Do not serve responses from cache if no-cache cache-control directive is set even for fresh responses
• Compute freshness lifetime from max-age cache-control directive
• Compute freshness lifetime from Expires response header
• Compute freshness lifetime from Last-Modified response header (heuristic used by Firefox)
• Compute current age from Age response header
• Compute current age from Date header
• Revalidate stale responses based on Last-Modified response header
• Revalidate stale responses based on ETag response header
• Set Date header for any received response missing it
what is missing:
• Pragma: no-cache support http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.1
• Vary header support http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.6
• Invalidation after updates or deletes http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.10
• ... probably others ..
In order to use this policy, set:
• HTTPCACHE_POLICY to scrapy.extensions.httpcache.RFC2616Policy
File system storage backend is available for the HTTP cache middleware.
In order to use this storage backend, set:
• HTTPCACHE_STORAGE to scrapy.extensions.httpcache.FilesystemCacheStorage
Each request/response pair is stored in a different directory containing the following files:
• request_body - the plain request body
• request_headers - the request headers (in raw HTTP format)
• response_body - the plain response body
• response_headers - the request headers (in raw HTTP format)
• meta - some metadata of this cache resource in Python repr() format (grep-friendly format)
• pickled_meta - the same metadata in meta but pickled for more efficient deserialization
The directory name is made from the request fingerprint (see scrapy.utils.request.fingerprint), and
one level of subdirectories is used to avoid creating too many files into the same directory (which is inefficient in many
file systems). An example directory could be:
/path/to/cache/dir/example.com/72/72811f648e718090f041317756c03adb0ada46c7
HTTPCACHE_ENABLED
HTTPCACHE_EXPIRATION_SECS
Default: 0
Expiration time for cached requests, in seconds.
Cached requests older than this time will be re-downloaded. If zero, cached requests will never expire.
Changed in version 0.11: Before 0.11, zero meant cached requests always expire.
HTTPCACHE_DIR
Default: 'httpcache'
The directory to use for storing the (low-level) HTTP cache. If empty, the HTTP cache will be disabled. If a relative
path is given, is taken relative to the project data dir. For more info see: Default structure of Scrapy projects.
HTTPCACHE_IGNORE_HTTP_CODES
HTTPCACHE_IGNORE_MISSING
Default: False
If enabled, requests not found in the cache will be ignored instead of downloaded.
HTTPCACHE_IGNORE_SCHEMES
HTTPCACHE_STORAGE
Default: 'scrapy.extensions.httpcache.FilesystemCacheStorage'
The class which implements the cache storage backend.
HTTPCACHE_DBM_MODULE
HTTPCACHE_POLICY
HTTPCACHE_GZIP
HttpCompressionMiddleware
class scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware
This middleware allows compressed (gzip, deflate) traffic to be sent/received from web sites.
HttpCompressionMiddleware Settings
COMPRESSION_ENABLED
Default: True
Whether the Compression middleware will be enabled.
ChunkedTransferMiddleware
class scrapy.downloadermiddlewares.chunked.ChunkedTransferMiddleware
This middleware adds support for chunked transfer encoding
HttpProxyMiddleware
RedirectMiddleware
class scrapy.downloadermiddlewares.redirect.RedirectMiddleware
This middleware handles redirection of requests based on response status.
The urls which the request goes through (while being redirected) can be found in the redirect_urls Request.
meta key.
The RedirectMiddleware can be configured through the following settings (see the settings documentation for
more info):
• REDIRECT_ENABLED
• REDIRECT_MAX_TIMES
If Request.meta has dont_redirect key set to True, the request will be ignored by this middleware.
RedirectMiddleware settings
REDIRECT_ENABLED
REDIRECT_MAX_TIMES
Default: 20
The maximum number of redirections that will be follow for a single request.
MetaRefreshMiddleware
class scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware
This middleware handles redirection of requests based on meta-refresh html tag.
The MetaRefreshMiddleware can be configured through the following settings (see the settings documentation
for more info):
• METAREFRESH_ENABLED
• METAREFRESH_MAXDELAY
This middleware obey REDIRECT_MAX_TIMES setting, dont_redirect and redirect_urls request meta
keys as described for RedirectMiddleware
MetaRefreshMiddleware settings
METAREFRESH_ENABLED
REDIRECT_MAX_METAREFRESH_DELAY
Default: 100
The maximum meta-refresh delay (in seconds) to follow the redirection.
RetryMiddleware
class scrapy.downloadermiddlewares.retry.RetryMiddleware
A middleware to retry failed requests that are potentially caused by temporary problems such as a connection
timeout or HTTP 500 error.
Failed pages are collected on the scraping process and rescheduled at the end, once the spider has finished crawl-
ing all regular (non failed) pages. Once there are no more failed pages to retry, this middleware sends a signal
(retry_complete), so other extensions could connect to that signal.
The RetryMiddleware can be configured through the following settings (see the settings documentation for more
info):
• RETRY_ENABLED
• RETRY_TIMES
• RETRY_HTTP_CODES
About HTTP errors to consider:
You may want to remove 400 from RETRY_HTTP_CODES, if you stick to the HTTP protocol. It’s included by
default because it’s a common code used to indicate server overload, which would be something we want to retry. If
Request.meta has dont_retry key set to True, the request will be ignored by this middleware.
RetryMiddleware Settings
RETRY_ENABLED
RETRY_TIMES
Default: 2
Maximum number of times to retry, in addition to the first download.
RETRY_HTTP_CODES
RobotsTxtMiddleware
class scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware
This middleware filters out requests forbidden by the robots.txt exclusion standard.
To make sure Scrapy respects robots.txt make sure the middleware is enabled and the ROBOTSTXT_OBEY
setting is enabled.
Warning: Keep in mind that, if you crawl using multiple concurrent requests per domain, Scrapy could
still download some forbidden pages if they were requested before the robots.txt file was downloaded. This
is a known limitation of the current robots.txt middleware and will be fixed in the future.
If Request.meta has dont_obey_robotstxt key set to True the request will be ignored by this middleware
even if ROBOTSTXT_OBEY is enabled.
DownloaderStats
class scrapy.downloadermiddlewares.stats.DownloaderStats
Middleware that stores stats of all requests, responses and exceptions that pass through it.
To use this middleware you must enable the DOWNLOADER_STATS setting.
UserAgentMiddleware
class scrapy.downloadermiddlewares.useragent.UserAgentMiddleware
Middleware that allows spiders to override the default user agent.
In order for a spider to override the default user agent, its user_agent attribute must be set.
AjaxCrawlMiddleware
class scrapy.downloadermiddlewares.ajaxcrawl.AjaxCrawlMiddleware
Middleware that finds ‘AJAX crawlable’ page variants based on meta-fragment html tag. See https://developers.
google.com/webmasters/ajax-crawling/docs/getting-started for more info.
Note: Scrapy finds ‘AJAX crawlable’ pages for URLs like 'http://example.com/!#foo=bar' even
without this middleware. AjaxCrawlMiddleware is necessary when URL doesn’t contain '!#'. This is often a
case for ‘index’ or ‘main’ website pages.
AjaxCrawlMiddleware Settings
AJAXCRAWL_ENABLED
Spider Middleware
The spider middleware is a framework of hooks into Scrapy’s spider processing mechanism where you can plug custom
functionality to process the responses that are sent to Spiders for processing and to process the requests and items that
are generated from spiders.
To activate a spider middleware component, add it to the SPIDER_MIDDLEWARES setting, which is a dict whose
keys are the middleware class path and their values are the middleware orders.
Here’s an example:
SPIDER_MIDDLEWARES = {
'myproject.middlewares.CustomSpiderMiddleware': 543,
}
The SPIDER_MIDDLEWARES setting is merged with the SPIDER_MIDDLEWARES_BASE setting defined in Scrapy
(and not meant to be overridden) and then sorted by order to get the final sorted list of enabled middlewares: the first
middleware is the one closer to the engine and the last is the one closer to the spider.
To decide which order to assign to your middleware see the SPIDER_MIDDLEWARES_BASE setting and pick a value
according to where you want to insert the middleware. The order does matter because each middleware performs a
different action and your middleware could depend on some previous (or subsequent) middleware being applied.
If you want to disable a builtin middleware (the ones defined in SPIDER_MIDDLEWARES_BASE, and enabled by de-
fault) you must define it in your project SPIDER_MIDDLEWARES setting and assign None as its value. For example,
if you want to disable the off-site middleware:
SPIDER_MIDDLEWARES = {
'myproject.middlewares.CustomSpiderMiddleware': 543,
'scrapy.spidermiddlewares.offsite.OffsiteMiddleware': None,
}
Finally, keep in mind that some middlewares may need to be enabled through a particular setting. See each middleware
documentation for more info.
Each middleware component is a Python class that defines one or more of the following methods:
class scrapy.spidermiddlewares.SpiderMiddleware
process_spider_input(response, spider)
This method is called for each response that goes through the spider middleware and into the spider, for
processing.
process_spider_input() should return None or raise an exception.
If it returns None, Scrapy will continue processing this response, executing all other middlewares until,
finally, the response is handed to the spider for processing.
If it raises an exception, Scrapy won’t bother calling any other spider middleware
process_spider_input() and will call the request errback. The output of the errback
is chained back in the other direction for process_spider_output() to process it, or
process_spider_exception() if it raised an exception.
Parameters
• response (Response object) – the response being processed
• spider (Spider object) – the spider for which this response is intended
process_spider_output(response, result, spider)
This method is called with the results returned from the Spider, after it has processed the response.
process_spider_output() must return an iterable of Request, dict or Item objects.
Parameters
• response (Response object) – the response which generated this output from the spi-
der
• result (an iterable of Request, dict or Item objects) – the result returned by the
spider
• spider (Spider object) – the spider whose result is being processed
process_spider_exception(response, exception, spider)
This method is called when when a spider or process_spider_input() method (from other spider
middleware) raises an exception.
process_spider_exception() should return either None or an iterable of Response, dict or
Item objects.
If it returns None, Scrapy will continue processing this exception, executing any other
process_spider_exception() in the following middleware components, until no middleware
components are left and the exception reaches the engine (where it’s logged and discarded).
If it returns an iterable the process_spider_output() pipeline kicks in, and no other
process_spider_exception() will be called.
Parameters
• response (Response object) – the response being processed when the exception was
raised
• exception (Exception object) – the exception raised
• spider (Spider object) – the spider which raised the exception
process_start_requests(start_requests, spider)
New in version 0.15.
This method is called with the start requests of the spider, and works similarly to the
process_spider_output() method, except that it doesn’t have a response associated and must
return only requests (not items).
It receives an iterable (in the start_requests parameter) and must return another iterable of
Request objects.
Note: When implementing this method in your spider middleware, you should always return an iterable
(that follows the input one) and not consume all start_requests iterator because it can be very large
(or even unbounded) and cause a memory overflow. The Scrapy engine is designed to pull start requests
while it has capacity to process them, so the start requests iterator can be effectively endless where there
is some other condition for stopping the spider (like a time limit or item/page count).
Parameters
• start_requests (an iterable of Request) – the start requests
• spider (Spider object) – the spider to whom the start requests belong
This page describes all spider middleware components that come with Scrapy. For information on how to use them
and how to write your own spider middleware, see the spider middleware usage guide.
For a list of the components enabled by default (and their orders) see the SPIDER_MIDDLEWARES_BASE setting.
DepthMiddleware
class scrapy.spidermiddlewares.depth.DepthMiddleware
DepthMiddleware is a scrape middleware used for tracking the depth of each Request inside the site being
scraped. It can be used to limit the maximum depth to scrape or things like that.
The DepthMiddleware can be configured through the following settings (see the settings documentation for
more info):
•DEPTH_LIMIT - The maximum depth that will be allowed to crawl for any site. If zero, no limit will be
imposed.
•DEPTH_STATS - Whether to collect depth stats.
•DEPTH_PRIORITY - Whether to prioritize the requests based on their depth.
HttpErrorMiddleware
class scrapy.spidermiddlewares.httperror.HttpErrorMiddleware
Filter out unsuccessful (erroneous) HTTP responses so that spiders don’t have to deal with them, which (most
of the time) imposes an overhead, consumes more resources, and makes the spider logic more complex.
According to the HTTP standard, successful responses are those whose status codes are in the 200-300 range.
If you still want to process response codes outside that range, you can specify which response codes the spider is able
to handle using the handle_httpstatus_list spider attribute or HTTPERROR_ALLOWED_CODES setting.
For example, if you want your spider to handle 404 responses you can do this:
class MySpider(CrawlSpider):
handle_httpstatus_list = [404]
The handle_httpstatus_list key of Request.meta can also be used to specify which response codes to
allow on a per-request basis. You can also set the meta key handle_httpstatus_all to True if you want to
allow any response code for a request.
Keep in mind, however, that it’s usually a bad idea to handle non-200 responses, unless you really know what you’re
doing.
For more information see: HTTP Status Code Definitions.
HttpErrorMiddleware settings
HTTPERROR_ALLOWED_CODES
Default: []
Pass all responses with non-200 status codes contained in this list.
HTTPERROR_ALLOW_ALL
Default: False
Pass all responses, regardless of its status code.
OffsiteMiddleware
class scrapy.spidermiddlewares.offsite.OffsiteMiddleware
Filters out Requests for URLs outside the domains covered by the spider.
This middleware filters out every request whose host names aren’t in the spider’s allowed_domains at-
tribute.
When your spider returns a request for a domain not belonging to those covered by the spider, this middleware
will log a debug message similar to this one:
DEBUG: Filtered offsite request to 'www.othersite.com': <GET http://www.othersite.
˓→com/some/page.html>
To avoid filling the log with too much noise, it will only print one of these messages for each new domain
filtered. So, for example, if another request for www.othersite.com is filtered, no log message will be
printed. But if a request for someothersite.com is filtered, a message will be printed (but only for the first
request filtered).
If the spider doesn’t define an allowed_domains attribute, or the attribute is empty, the offsite middleware
will allow all requests.
If the request has the dont_filter attribute set, the offsite middleware will allow the request even if its
domain is not listed in allowed domains.
RefererMiddleware
class scrapy.spidermiddlewares.referer.RefererMiddleware
Populates Request Referer header, based on the URL of the Response which generated it.
RefererMiddleware settings
REFERER_ENABLED
UrlLengthMiddleware
class scrapy.spidermiddlewares.urllength.UrlLengthMiddleware
Filters out requests with URLs longer than URLLENGTH_LIMIT
The UrlLengthMiddleware can be configured through the following settings (see the settings documenta-
tion for more info):
•URLLENGTH_LIMIT - The maximum URL length to allow for crawled URLs.
Extensions
The extensions framework provides a mechanism for inserting your own custom functionality into Scrapy.
Extensions are just regular classes that are instantiated at Scrapy startup, when extensions are initialized.
Extension settings
Extensions use the Scrapy settings to manage their settings, just like any other Scrapy code.
It is customary for extensions to prefix their settings with their own name, to avoid collision with existing (and fu-
ture) extensions. For example, a hypothetic extension to handle Google Sitemaps would use settings like GOOGLE-
SITEMAP_ENABLED, GOOGLESITEMAP_DEPTH, and so on.
Extensions are loaded and activated at startup by instantiating a single instance of the extension class. Therefore, all
the extension initialization code must be performed in the class constructor (__init__ method).
To make an extension available, add it to the EXTENSIONS setting in your Scrapy settings. In EXTENSIONS, each
extension is represented by a string: the full Python path to the extension’s class name. For example:
EXTENSIONS = {
'scrapy.extensions.corestats.CoreStats': 500,
'scrapy.telnet.TelnetConsole': 500,
}
As you can see, the EXTENSIONS setting is a dict where the keys are the extension paths, and their values are the
orders, which define the extension loading order. Extensions orders are not as important as middleware orders though,
and they are typically irrelevant, ie. it doesn’t matter in which order the extensions are loaded because they don’t
depend on each other [1].
However, this feature can be exploited if you need to add an extension which depends on other extensions already
loaded.
[1] This is is why the EXTENSIONS_BASE setting in Scrapy (which contains all built-in extensions enabled by
default) defines all the extensions with the same order (500).
Not all available extensions will be enabled. Some of them usually depend on a particular setting. For example, the
HTTP Cache extension is available by default but disabled unless the HTTPCACHE_ENABLED setting is set.
Disabling an extension
In order to disable an extension that comes enabled by default (ie. those included in the EXTENSIONS_BASE setting)
you must set its order to None. For example:
EXTENSIONS = {
'scrapy.extensions.corestats.CoreStats': None,
}
Each extension is a Python class. The main entry point for a Scrapy extension (this also includes middlewares and
pipelines) is the from_crawler class method which receives a Crawler instance. Through the Crawler object
you can access settings, signals, stats, and also control the crawling behaviour.
Typically, extensions connect to signals and perform tasks triggered by them.
Finally, if the from_crawler method raises the NotConfigured exception, the extension will be disabled. Oth-
erwise, the extension will be enabled.
Sample extension
Here we will implement a simple extension to illustrate the concepts described in the previous section. This extension
will log a message every time:
• a spider is opened
• a spider is closed
• a specific number of items are scraped
The extension will be enabled through the MYEXT_ENABLED setting and the number of items will be specified through
the MYEXT_ITEMCOUNT setting.
Here is the code of such extension:
import logging
from scrapy import signals
from scrapy.exceptions import NotConfigured
logger = logging.getLogger(__name__)
class SpiderOpenCloseLogging(object):
@classmethod
def from_crawler(cls, crawler):
# first check if the extension should be enabled and raise
# NotConfigured otherwise
if not crawler.settings.getbool('MYEXT_ENABLED'):
raise NotConfigured
self.items_scraped += 1
if self.items_scraped % self.item_count == 0:
logger.info("scraped %d items", self.items_scraped)
class scrapy.extensions.logstats.LogStats
Log basic stats like crawled pages and scraped items.
class scrapy.extensions.corestats.CoreStats
Enable the collection of core statistics, provided the stats collection is enabled (see Stats Collection).
class scrapy.telnet.TelnetConsole
Provides a telnet console for getting into a Python interpreter inside the currently running Scrapy process, which can
be very useful for debugging.
The telnet console must be enabled by the TELNETCONSOLE_ENABLED setting, and the server will listen in the port
specified in TELNETCONSOLE_PORT.
class scrapy.extensions.memusage.MemoryUsage
Monitors the memory used by the Scrapy process that runs the spider and:
1. sends a notification e-mail when it exceeds a certain value
2. closes the spider when it exceeds a certain value
The notification e-mails can be triggered when a certain warning value is reached (MEMUSAGE_WARNING_MB) and
when the maximum value is reached (MEMUSAGE_LIMIT_MB) which will also cause the spider to be closed and the
Scrapy process to be terminated.
This extension is enabled by the MEMUSAGE_ENABLED setting and can be configured with the following settings:
• MEMUSAGE_LIMIT_MB
• MEMUSAGE_WARNING_MB
• MEMUSAGE_NOTIFY_MAIL
• MEMUSAGE_REPORT
class scrapy.extensions.memdebug.MemoryDebugger
An extension for debugging memory usage. It collects information about:
• objects uncollected by the Python garbage collector
• objects left alive that shouldn’t. For more info, see Debugging memory leaks with trackref
To enable this extension, turn on the MEMDEBUG_ENABLED setting. The info will be stored in the stats.
class scrapy.extensions.closespider.CloseSpider
Closes a spider automatically when some conditions are met, using a specific closing reason for each condition.
The conditions for closing a spider can be configured through the following settings:
• CLOSESPIDER_TIMEOUT
• CLOSESPIDER_ITEMCOUNT
• CLOSESPIDER_PAGECOUNT
• CLOSESPIDER_ERRORCOUNT
CLOSESPIDER_TIMEOUT
Default: 0
An integer which specifies a number of seconds. If the spider remains open for more than that number of second, it
will be automatically closed with the reason closespider_timeout. If zero (or non set), spiders won’t be closed
by timeout.
CLOSESPIDER_ITEMCOUNT
Default: 0
An integer which specifies a number of items. If the spider scrapes more than that amount if items and those items are
passed by the item pipeline, the spider will be closed with the reason closespider_itemcount. If zero (or non
set), spiders won’t be closed by number of passed items.
CLOSESPIDER_PAGECOUNT
CLOSESPIDER_ERRORCOUNT
StatsMailer extension
class scrapy.extensions.statsmailer.StatsMailer
This simple extension can be used to send a notification e-mail every time a domain has finished scraping, including
the Scrapy stats collected. The email will be sent to all recipients specified in the STATSMAILER_RCPTS setting.
Debugging extensions
class scrapy.extensions.debug.StackTraceDump
Dumps information about the running process when a SIGQUIT or SIGUSR2 signal is received. The information
dumped is the following:
1. engine status (using scrapy.utils.engine.get_engine_status())
2. live references (see Debugging memory leaks with trackref )
3. stack trace of all threads
After the stack trace and engine status is dumped, the Scrapy process continues running normally.
This extension only works on POSIX-compliant platforms (ie. not Windows), because the SIGQUIT and SIGUSR2
signals are not available on Windows.
There are at least two ways to send Scrapy the SIGQUIT signal:
1. By pressing Ctrl-while a Scrapy process is running (Linux only?)
2. By running this command (assuming <pid> is the process id of the Scrapy process):
Debugger extension
class scrapy.extensions.debug.Debugger
Invokes a Python debugger inside a running Scrapy process when a SIGUSR2 signal is received. After the debugger
is exited, the Scrapy process continues running normally.
For more info see Debugging in Python.
This extension only works on POSIX-compliant platforms (ie. not Windows).
Core API
Crawler API
The main entry point to Scrapy API is the Crawler object, passed to extensions through the from_crawler class
method. This object provides access to all Scrapy core components, and it’s the only way for extensions to access
them and hook their functionality into Scrapy. The Extension Manager is responsible for loading and keeping track of
installed extensions and it’s configured through the EXTENSIONS setting which contains a dictionary of all available
extensions and their order similar to how you configure the downloader middlewares.
class scrapy.crawler.Crawler(spidercls, settings)
The Crawler object must be instantiated with a scrapy.spiders.Spider subclass and a scrapy.
settings.Settings object.
settings
The settings manager of this crawler.
This is used by extensions & middlewares to access the Scrapy settings of this crawler.
For an introduction on Scrapy settings see Settings.
For the API see Settings class.
signals
The signals manager of this crawler.
This is used by extensions & middlewares to hook themselves into Scrapy functionality.
For an introduction on signals see Signals.
For the API see SignalManager class.
stats
The stats collector of this crawler.
This is used from extensions & middlewares to record stats of their behaviour, or access stats collected by
other extensions.
For an introduction on stats collection see Stats Collection.
For the API see StatsCollector class.
extensions
The extension manager that keeps track of enabled extensions.
Most extensions won’t need to access this attribute.
For an introduction on extensions and a list of available extensions on Scrapy see Extensions.
engine
The execution engine, which coordinates the core crawling logic between the scheduler, downloader and
spiders.
Some extension may want to access the Scrapy engine, to inspect or modify the downloader and scheduler
behaviour, although this is an advanced use and this API is not yet stable.
spider
Spider currently being crawled. This is an instance of the spider class provided while constructing the
crawler, and it is created after the arguments given in the crawl() method.
crawl(*args, **kwargs)
Starts the crawler by instantiating its spider class with the given args and kwargs arguments, while setting
the execution engine in motion.
Returns a deferred that is fired when the crawl is finished.
class scrapy.crawler.CrawlerRunner(settings=None)
This is a convenient helper class that keeps track of, manages and runs crawlers inside an already setup Twisted
reactor.
The CrawlerRunner object must be instantiated with a Settings object.
This class shouldn’t be needed (since Scrapy is responsible of using it accordingly) unless writing scripts that
manually handle the crawling process. See Run Scrapy from a script for an example.
crawl(crawler_or_spidercls, *args, **kwargs)
Run a crawler with the provided arguments.
It will call the given Crawler’s crawl() method, while keeping track of it so it can be stopped later.
If crawler_or_spidercls isn’t a Crawler instance, this method will try to create one using this parameter
as the spider class given to it.
Returns a deferred that is fired when the crawling is finished.
Parameters
• crawler_or_spidercls (Crawler instance, Spider subclass or string) – already
created crawler, or a spider class or spider’s name inside the project to create it
• args (list) – arguments to initialize the spider
• kwargs (dict) – keyword arguments to initialize the spider
crawlers
Set of crawlers started by crawl() and managed by this class.
join()
Returns a deferred that is fired when all managed crawlers have completed their executions.
stop()
Stops simultaneously all the crawling jobs taking place.
Returns a deferred that is fired when they all have ended.
class scrapy.crawler.CrawlerProcess(settings=None)
Bases: scrapy.crawler.CrawlerRunner
A class to run multiple scrapy crawlers in a process simultaneously.
This class extends CrawlerRunner by adding support for starting a Twisted reactor and handling shutdown
signals, like the keyboard interrupt command Ctrl-C. It also configures top-level logging.
This utility should be a better fit than CrawlerRunner if you aren’t running another Twisted reactor within
your application.
The CrawlerProcess object must be instantiated with a Settings object.
This class shouldn’t be needed (since Scrapy is responsible of using it accordingly) unless writing scripts that
manually handle the crawling process. See Run Scrapy from a script for an example.
Settings API
scrapy.settings.SETTINGS_PRIORITIES
Dictionary that sets the key name and priority level of the default settings priorities used in Scrapy.
Each item defines a settings entry point, giving it a code name for identification and an integer priority. Greater
priorities take more precedence over lesser ones when setting and retrieving values in the Settings class.
SETTINGS_PRIORITIES = {
'default': 0,
'command': 10,
'project': 20,
'spider': 30,
'cmdline': 40,
}
After instantiation of this class, the new object will have the global default settings described on Built-in settings
reference already populated.
Additional values can be passed on initialization with the values argument, and they would take
the priority level. If the latter argument is a string, the priority name will be looked up in
SETTINGS_PRIORITIES. Otherwise, a expecific integer should be provided.
Once the object is created, new settings can be loaded or updated with the set() method, and can be ac-
cessed with the square bracket notation of dictionaries, or with the get() method of the instance and its value
conversion variants. When requesting a stored key, the value with the highest priority will be retrieved.
set(name, value, priority=’project’)
Store a key/value attribute with a given priority.
Settings should be populated before configuring the Crawler object (through the configure() method),
otherwise they won’t have any effect.
Parameters
• name (string) – the setting name
• value (any) – the value to associate with the setting
• priority (string or int) – the priority of the setting. Should be a key of
SETTINGS_PRIORITIES or an integer
setdict(values, priority=’project’)
Store key/value pairs with a given priority.
This is a helper function that calls set() for every item of values with the provided priority.
Parameters
• values (dict) – the settings names and values
• priority (string or int) – the priority of the settings. Should be a key of
SETTINGS_PRIORITIES or an integer
setmodule(module, priority=’project’)
Store settings from a module with a given priority.
This is a helper function that calls set() for every globally declared uppercase variable of module with
the provided priority.
Parameters
• module (module object or string) – the module or the path of the module
• priority (string or int) – the priority of the settings. Should be a key of
SETTINGS_PRIORITIES or an integer
get(name, default=None)
Get a setting value without affecting its original type.
Parameters
• name (string) – the setting name
• default (any) – the value to return if no setting is found
getbool(name, default=False)
Get a setting value as a boolean. For example, both 1 and '1', and True return True, while 0, '0',
False and None return False``
For example, settings populated through environment variables set to '0' will return False when using
this method.
Parameters
• name (string) – the setting name
• default (any) – the value to return if no setting is found
getint(name, default=0)
Get a setting value as an int
Parameters
• name (string) – the setting name
• default (any) – the value to return if no setting is found
getfloat(name, default=0.0)
Get a setting value as a float
Parameters
• name (string) – the setting name
• default (any) – the value to return if no setting is found
getlist(name, default=None)
Get a setting value as a list. If the setting original type is a list, a copy of it will be returned. If it’s a string
it will be split by ”,”.
For example, settings populated through environment variables set to 'one,two' will return a list [’one’,
‘two’] when using this method.
Parameters
• name (string) – the setting name
• default (any) – the value to return if no setting is found
getdict(name, default=None)
Get a setting value as a dictionary. If the setting original type is a dictionary, a copy of it will be returned.
If it’s a string it will evaluated as a json dictionary.
Parameters
• name (string) – the setting name
• default (any) – the value to return if no setting is found
copy()
Make a deep copy of current settings.
This method returns a new instance of the Settings class, populated with the same values and their
priorities.
Modifications to the new object won’t be reflected on the original settings.
freeze()
Disable further changes to the current settings.
After calling this method, the present state of the settings will become immutable. Trying to change values
through the set() method and its variants won’t be possible and will be alerted.
frozencopy()
Return an immutable copy of the current settings.
Alias for a freeze() call in the object returned by copy()
SpiderLoader API
class scrapy.loader.SpiderLoader
This class is in charge of retrieving and handling the spider classes defined across the project.
Custom spider loaders can be employed by specifying their path in the SPIDER_LOADER_CLASS project
setting. They must fully implement the scrapy.interfaces.ISpiderLoader interface to guarantee an
errorless execution.
from_settings(settings)
This class method is used by Scrapy to create an instance of the class. It’s called with the current project
settings, and it loads the spiders found in the modules of the SPIDER_MODULES setting.
Parameters settings (Settings instance) – project settings
load(spider_name)
Get the Spider class with the given name. It’ll look into the previously loaded spiders for a spider class
with name spider_name and will raise a KeyError if not found.
Parameters spider_name (str) – spider class name
list()
Get the names of the available spiders in the project.
find_by_request(request)
List the spiders’ names that can handle the given request. Will try to match the request’s url against the
domains of the spiders.
Parameters request (Request instance) – queried request
Signals API
class scrapy.signalmanager.SignalManager
connect(receiver, signal)
Connect a receiver function to a signal.
The signal can be any object, although Scrapy comes with some predefined signals that are documented in
the Signals section.
Parameters
• receiver (callable) – the function to be connected
• signal (object) – the signal to connect to
send_catch_log(signal, **kwargs)
Send a signal, catch exceptions and log them.
The keyword arguments are passed to the signal handlers (connected through the connect() method).
send_catch_log_deferred(signal, **kwargs)
Like send_catch_log() but supports returning deferreds from signal handlers.
Returns a deferred that gets fired once all signal handlers deferreds were fired. Send a signal, catch excep-
tions and log them.
The keyword arguments are passed to the signal handlers (connected through the connect() method).
disconnect(receiver, signal)
Disconnect a receiver function from a signal. This has the opposite effect of the connect() method, and
the arguments are the same.
disconnect_all(signal)
Disconnect all receivers from the given signal.
Parameters signal (object) – the signal to disconnect from
There are several Stats Collectors available under the scrapy.statscollectors module and they all implement
the Stats Collector API defined by the StatsCollector class (which they all inherit from).
class scrapy.statscollectors.StatsCollector
get_value(key, default=None)
Return the value for the given stats key or default if it doesn’t exist.
get_stats()
Get all stats from the currently running spider as a dict.
set_value(key, value)
Set the given value for the given stats key.
set_stats(stats)
Override the current stats with the dict passed in stats argument.
inc_value(key, count=1, start=0)
Increment the value of the given stats key, by the given count, assuming the start value given (when it’s not
set).
max_value(key, value)
Set the given value for the given key only if current value for the same key is lower than value. If there is
no current value for the given key, the value is always set.
min_value(key, value)
Set the given value for the given key only if current value for the same key is greater than value. If there is
no current value for the given key, the value is always set.
clear_stats()
Clear all stats.
The following methods are not part of the stats collection api but instead used when implementing custom stats
collectors:
open_spider(spider)
Open the given spider for stats collection.
close_spider(spider)
Close the given spider. After this is called, no more specific stats can be accessed or collected.
Signals
Scrapy uses signals extensively to notify when certain events occur. You can catch some of those signals in your
Scrapy project (using an extension, for example) to perform additional tasks or extend Scrapy to add functionality not
provided out of the box.
Even though signals provide several arguments, the handlers that catch them don’t need to accept all of them - the
signal dispatching mechanism will only deliver the arguments that the handler receives.
You can connect to signals (or send your own) through the Signals API.
Some signals support returning Twisted deferreds from their handlers, see the Built-in signals reference below to know
which ones.
engine_started
scrapy.signals.engine_started()
Sent when the Scrapy engine has started crawling.
This signal supports returning deferreds from their handlers.
Note: This signal may be fired after the spider_opened signal, depending on how the spider was started. So
don’t rely on this signal getting fired before spider_opened.
engine_stopped
scrapy.signals.engine_stopped()
Sent when the Scrapy engine is stopped (for example, when a crawling process has finished).
This signal supports returning deferreds from their handlers.
item_scraped
item_dropped
spider_closed
scrapy.signals.spider_closed(spider, reason)
Sent after a spider has been closed. This can be used to release per-spider resources reserved on
spider_opened.
This signal supports returning deferreds from their handlers.
Parameters
• spider (Spider object) – the spider which has been closed
• reason (str) – a string which describes the reason why the spider was closed. If it was
closed because the spider has completed scraping, the reason is 'finished'. Otherwise,
if the spider was manually closed by calling the close_spider engine method, then
the reason is the one passed in the reason argument of that method (which defaults to
'cancelled'). If the engine was shutdown (for example, by hitting Ctrl-C to stop it) the
reason will be 'shutdown'.
spider_opened
scrapy.signals.spider_opened(spider)
Sent after a spider has been opened for crawling. This is typically used to reserve per-spider resources, but can
be used for any task that needs to be performed when a spider is opened.
This signal supports returning deferreds from their handlers.
Parameters spider (Spider object) – the spider which has been opened
spider_idle
scrapy.signals.spider_idle(spider)
Sent when a spider has gone idle, which means the spider has no further:
•requests waiting to be downloaded
•requests scheduled
•items being processed in the item pipeline
If the idle state persists after all handlers of this signal have finished, the engine starts closing the spider. After
the spider has finished closing, the spider_closed signal is sent.
You can, for example, schedule some requests in your spider_idle handler to prevent the spider from being
closed.
This signal does not support returning deferreds from their handlers.
Parameters spider (Spider object) – the spider which has gone idle
spider_error
This signal does not support returning deferreds from their handlers.
Parameters
• failure (Failure object) – the exception raised as a Twisted Failure object
• response (Response object) – the response being processed when the exception was
raised
• spider (Spider object) – the spider which raised the exception
request_scheduled
scrapy.signals.request_scheduled(request, spider)
Sent when the engine schedules a Request, to be downloaded later.
The signal does not support returning deferreds from their handlers.
Parameters
• request (Request object) – the request that reached the scheduler
• spider (Spider object) – the spider that yielded the request
request_dropped
scrapy.signals.request_dropped(request, spider)
Sent when a Request, scheduled by the engine to be downloaded later, is rejected by the scheduler.
The signal does not support returning deferreds from their handlers.
Parameters
• request (Request object) – the request that reached the scheduler
• spider (Spider object) – the spider that yielded the request
response_received
response_downloaded
Item Exporters
Once you have scraped your items, you often want to persist or export those items, to use the data in some other
application. That is, after all, the whole purpose of the scraping process.
For this purpose Scrapy provides a collection of Item Exporters for different output formats, such as XML, CSV or
JSON.
If you are in a hurry, and just want to use an Item Exporter to output scraped data see the Feed exports. Otherwise, if
you want to know how Item Exporters work or need more custom functionality (not covered by the default exports),
continue reading below.
In order to use an Item Exporter, you must instantiate it with its required args. Each Item Exporter requires different
arguments, so check each exporter documentation to be sure, in Built-in Item Exporters reference. After you have
instantiated your exporter, you have to:
1. call the method start_exporting() in order to signal the beginning of the exporting process
2. call the export_item() method for each item you want to export
3. and finally call the finish_exporting() to signal the end of the exporting process
Here you can see an Item Pipeline which uses an Item Exporter to export scraped items to different files, one per
spider:
class XmlExportPipeline(object):
def __init__(self):
self.files = {}
@classmethod
def from_crawler(cls, crawler):
pipeline = cls()
crawler.signals.connect(pipeline.spider_opened, signals.spider_opened)
crawler.signals.connect(pipeline.spider_closed, signals.spider_closed)
return pipeline
file.close()
By default, the field values are passed unmodified to the underlying serialization library, and the decision of how to
serialize them is delegated to each particular serialization library.
However, you can customize how each field value is serialized before it is passed to the serialization library.
There are two ways to customize how a field will be serialized, which are described next.
If you use Item you can declare a serializer in the field metadata. The serializer must be a callable which receives a
value and returns its serialized form.
Example:
import scrapy
def serialize_price(value):
return '$ %s' % str(value)
class Product(scrapy.Item):
name = scrapy.Field()
price = scrapy.Field(serializer=serialize_price)
You can also override the serialize_field() method to customize how your field value will be exported.
Make sure you call the base class serialize_field() method after your custom code.
Example:
class ProductXmlExporter(XmlItemExporter):
Here is a list of the Item Exporters bundled with Scrapy. Some of them contain output examples, which assume you’re
exporting these two items:
BaseItemExporter
always serialized to str using this encoding). Other value types are passed unchanged to the specific
serialization library.
XmlItemExporter
Unless overridden in the serialize_field() method, multi-valued fields are exported by serializing each
value inside a <value> element. This is for convenience, as multi-valued fields are very common.
For example, the item:
CsvItemExporter
be used to define the CSV columns and their order. The export_empty_fields attribute has no effect on
this exporter.
Parameters
• file – the file-like object to use for exporting the data.
• include_headers_line (str) – If enabled, makes the exporter output a header line
with the field names taken from BaseItemExporter.fields_to_export or the
first exported item fields.
• join_multivalued – The char (or chars) that will be used for joining multi-valued
fields, if found.
The additional keyword arguments of this constructor are passed to the BaseItemExporter constructor,
and the leftover arguments to the csv.writer constructor, so you can use any csv.writer constructor argument to
customize this exporter.
A typical output of this exporter would be:
product,price
Color TV,1200
DVD player,200
PickleItemExporter
PprintItemExporter
JsonItemExporter
Warning: JSON is very simple and flexible serialization format, but it doesn’t scale well for large amounts
of data since incremental (aka. stream-mode) parsing is not well supported (if at all) among JSON parsers (on
any language), and most of them just parse the entire object in memory. If you want the power and simplicity
of JSON with a more stream-friendly format, consider using JsonLinesItemExporter instead, or
splitting the output in multiple chunks.
JsonLinesItemExporter
Unlike the one produced by JsonItemExporter, the format produced by this exporter is well suited for
serializing large amounts of data.
Architecture overview Understand the Scrapy architecture.
Downloader Middleware Customize how pages get requested and downloaded.
Spider Middleware Customize the input and output of your spiders.
Extensions Extend Scrapy with your custom functionality
Core API Use it on extensions and middlewares to extend Scrapy functionality
Signals See all available signals and how to work with them.
Item Exporters Quickly export your scraped items to a file (XML, CSV, etc).
Release notes
1.0.7 (2017-03-03)
1.0.6 (2016-05-04)
• FIX: RetryMiddleware is now robust to non-standard HTTP status codes (issue 1857)
• FIX: Filestorage HTTP cache was checking wrong modified time (issue 1875)
• DOC: Support for Sphinx 1.4+ (issue 1893)
• DOC: Consistency in selectors examples (issue 1869)
1.0.5 (2016-02-04)
• FIX: [Backport] Ignore bogus links in LinkExtractors (fixes issue 907, commit 108195e)
• TST: Changed buildbot makefile to use ‘pytest’ (commit 1f3d90a)
• DOC: Fixed typos in tutorial and media-pipeline (commit 808a9ea and commit 803bd87)
• DOC: Add AjaxCrawlMiddleware to DOWNLOADER_MIDDLEWARES_BASE in settings docs (commit
aa94121)
1.0.4 (2015-12-30)
193
Scrapy Documentation, Release 1.0.7
1.0.3 (2015-08-11)
1.0.2 (2015-08-06)
• Twisted 15.3.0 does not raises PicklingError serializing lambda functions (commit b04dd7d)
• Minor method name fix (commit 6f85c7f)
• minor: scrapy.Spider grammar and clarity (commit 9c9d2e0)
• Put a blurb about support channels in CONTRIBUTING (commit c63882b)
• Fixed typos (commit a9ae7b0)
• Fix doc reference. (commit 7c8a4fe)
1.0.1 (2015-07-01)
• Unquote request path before passing to FTPClient, it already escape paths (commit cc00ad2)
• include tests/ to source distribution in MANIFEST.in (commit eca227e)
• DOC Fix SelectJmes documentation (commit b8567bc)
• DOC Bring Ubuntu and Archlinux outside of Windows subsection (commit 392233f)
• DOC remove version suffix from ubuntu package (commit 5303c66)
• DOC Update release date for 1.0 (commit c89fa29)
1.0.0 (2015-06-19)
You will find a lot of new features and bugfixes in this major release. Make sure to check our updated overview to get
a glance of some of the changes, along with our brushed tutorial.
Declaring and returning Scrapy Items is no longer necessary to collect the scraped data from your spider, you can now
return explicit dictionaries instead.
Classic version
class MyItem(scrapy.Item):
url = scrapy.Field()
class MySpider(scrapy.Spider):
def parse(self, response):
return MyItem(url=response.url)
New version
class MySpider(scrapy.Spider):
def parse(self, response):
return {'url': response.url}
Last Google Summer of Code project accomplished an important redesign of the mechanism used for populating
settings, introducing explicit priorities to override any given setting. As an extension of that goal, we included a new
level of priority for settings that act exclusively for a single spider, allowing them to redefine project settings.
Start using it by defining a custom_settings class variable in your spider:
class MySpider(scrapy.Spider):
custom_settings = {
"DOWNLOAD_DELAY": 5.0,
"RETRY_ENABLED": False,
}
Python Logging
Scrapy 1.0 has moved away from Twisted logging to support Python built in’s as default logging system. We’re
maintaining backward compatibility for most of the old custom interface to call logging functions, but you’ll get
warnings to switch to the Python logging API entirely.
Old version
New version
import logging
logging.info('MESSAGE')
Logging with spiders remains the same, but on top of the log() method you’ll have access to a custom logger
created for the spider to issue log events:
class MySpider(scrapy.Spider):
def parse(self, response):
self.logger.info('Response received')
Another milestone for last Google Summer of Code was a refactoring of the internal API, seeking a simpler and easier
usage. Check new core interface in: Core API
A common situation where you will face these changes is while running Scrapy from scripts. Here’s a quick example
of how to run a Spider manually with the new API:
process = CrawlerProcess({
'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'
})
process.crawl(MySpider)
process.start()
Bear in mind this feature is still under development and its API may change until it reaches a stable status.
See more examples for scripts running Scrapy: Common Practices
Module Relocations
There’s been a large rearrangement of modules trying to improve the general structure of Scrapy. Main changes were
separating various subpackages into new projects and dissolving both scrapy.contrib and scrapy.contrib_exp into top
level packages. Backward compatibility was kept among internal relocations, while importing deprecated modules
expect warnings indicating their new place.
Outsourced packages
Note: These extensions went through some minor changes, e.g. some setting names were changed. Please check the
documentation in each new repository to get familiar with the new usage.
Changelog
0.24.6 (2015-04-20)
0.24.5 (2015-02-25)
0.24.4 (2014-08-09)
• pem file is used by mockserver and required by scrapy bench (commit 5eddc68)
• scrapy bench needs scrapy.tests* (commit d6cb999)
0.24.3 (2014-08-09)
0.24.2 (2014-07-08)
• Use a mutable mapping to proxy deprecated settings.overrides and settings.defaults attribute (commit e5e8133)
• there is not support for python3 yet (commit 3cd6146)
• Update python compatible version set to debian packages (commit fa5d76b)
• DOC fix formatting in release notes (commit c6a9e20)
0.24.1 (2014-06-27)
• Fix deprecated CrawlerSettings and increase backwards compatibility with .defaults attribute (commit 8e3f20a)
0.24.0 (2014-06-26)
Enhancements
• Add a setting to control what class is instanciated as Downloader component (issue 738)
• Pass response in item_dropped signal (issue 724)
• Improve scrapy check contracts command (issue 733, issue 752)
• Document spider.closed() shortcut (issue 719)
• Document request_scheduled signal (issue 746)
• Add a note about reporting security issues (issue 697)
• Add LevelDB http cache storage backend (issue 626, issue 500)
• Sort spider list output of scrapy list command (issue 742)
• Multiple documentation enhancemens and fixes (issue 575, issue 587, issue 590, issue 596, issue 610, issue 617,
issue 618, issue 627, issue 613, issue 643, issue 654, issue 675, issue 663, issue 711, issue 714)
Bugfixes
• Encode unicode URL value when creating Links in RegexLinkExtractor (issue 561)
• Ignore None values in ItemLoader processors (issue 556)
• Fix link text when there is an inner tag in SGMLLinkExtractor and HtmlParserLinkExtractor (issue 485, issue
574)
• Fix wrong checks on subclassing of deprecated classes (issue 581, issue 584)
• Handle errors caused by inspect.stack() failures (issue 582)
• Fix a reference to unexistent engine attribute (issue 593, issue 594)
• Fix dynamic itemclass example usage of type() (issue 603)
• Use lucasdemarchi/codespell to fix typos (issue 628)
• Fix default value of attrs argument in SgmlLinkExtractor to be tuple (issue 661)
• Fix XXE flaw in sitemap reader (issue 676)
• Fix engine to support filtered start requests (issue 707)
• Fix offsite middleware case on urls with no hostnames (issue 745)
• Testsuite doesn’t require PIL anymore (issue 585)
• Fix wrong checks on subclassing of deprecated classes. closes #581 (commit 46d98d6)
• Docs: 4-space indent for final spider example (commit 13846de)
• Fix HtmlParserLinkExtractor and tests after #485 merge (commit 368a946)
• BaseSgmlLinkExtractor: Fixed the missing space when the link has an inner tag (commit b566388)
• BaseSgmlLinkExtractor: Added unit test of a link with an inner tag (commit c1cb418)
• BaseSgmlLinkExtractor: Fixed unknown_endtag() so that it only set current_link=None when the end tag match
the opening tag (commit 7e4d627)
• Fix tests for Travis-CI build (commit 76c7e20)
• replace unencodeable codepoints with html entities. fixes #562 and #285 (commit 5f87b17)
• RegexLinkExtractor: encode URL unicode value when creating Links (commit d0ee545)
• Updated the tutorial crawl output with latest output. (commit 8da65de)
• Updated shell docs with the crawler reference and fixed the actual shell output. (commit 875b9ab)
• PEP8 minor edits. (commit f89efaf)
• Expose current crawler in the scrapy shell. (commit 5349cec)
• Unused re import and PEP8 minor edits. (commit 387f414)
• Ignore None’s values when using the ItemLoader. (commit 0632546)
• DOC Fixed HTTPCACHE_STORAGE typo in the default value which is now Filesystem instead Dbm. (commit
cde9a8c)
• show ubuntu setup instructions as literal code (commit fb5c9c5)
• Update Ubuntu installation instructions (commit 70fb105)
• Merge pull request #550 from stray-leone/patch-1 (commit 6f70b6a)
• modify the version of scrapy ubuntu package (commit 725900d)
• fix 0.22.0 release date (commit af0219a)
• fix typos in news.rst and remove (not released yet) header (commit b7f58f4)
Enhancements
• [Backwards incompatible] Switched HTTPCacheMiddleware backend to filesystem (issue 541) To restore old
backend set HTTPCACHE_STORAGE to scrapy.contrib.httpcache.DbmCacheStorage
• Proxy https:// urls using CONNECT method (issue 392, issue 397)
• Add a middleware to crawl ajax crawleable pages as defined by google (issue 343)
• Rename scrapy.spider.BaseSpider to scrapy.spider.Spider (issue 510, issue 519)
• Selectors register EXSLT namespaces by default (issue 472)
• Unify item loaders similar to selectors renaming (issue 461)
• Make RFPDupeFilter class easily subclassable (issue 533)
• Improve test coverage and forthcoming Python 3 support (issue 525)
• Promote startup info on settings and middleware to INFO level (issue 520)
• Support partials in get_func_args util (issue 506, issue:504)
• Allow running indiviual tests via tox (issue 503)
• Update extensions ignored by link extractors (issue 498)
• Add middleware methods to get files/images/thumbs paths (issue 490)
• Improve offsite middleware tests (issue 478)
• Add a way to skip default Referer header set by RefererMiddleware (issue 475)
• Do not send x-gzip in default Accept-Encoding header (issue 469)
• Support defining http error handling using settings (issue 466)
• Use modern python idioms wherever you find legacies (issue 497)
• Improve and correct documentation (issue 527, issue 524, issue 521, issue 517, issue 512, issue 505, issue 502,
issue 489, issue 465, issue 460, issue 425, issue 536)
Fixes
Enhancements
• New Selector’s API including CSS selectors (issue 395 and issue 426),
• Request/Response url/body attributes are now immutable (modifying them had been deprecated for a long time)
• ITEM_PIPELINES is now defined as a dict (instead of a list)
• Sitemap spider can fetch alternate URLs (issue 360)
• Selector.remove_namespaces() now remove namespaces from element’s attributes. (issue 416)
• Paved the road for Python 3.3+ (issue 435, issue 436, issue 431, issue 452)
• New item exporter using native python types with nesting support (issue 366)
• Tune HTTP1.1 pool size so it matches concurrency defined by settings (commit b43b5f575)
• scrapy.mail.MailSender now can connect over TLS or upgrade using STARTTLS (issue 327)
• New FilesPipeline with functionality factored out from ImagesPipeline (issue 370, issue 409)
• Recommend Pillow instead of PIL for image handling (issue 317)
• Added debian packages for Ubuntu quantal and raring (commit 86230c0)
• Mock server (used for tests) can listen for HTTPS requests (issue 410)
• Remove multi spider support from multiple core components (issue 422, issue 421, issue 420, issue 419, issue
423, issue 418)
• Travis-CI now tests Scrapy changes against development versions of w3lib and queuelib python packages.
• Add pypy 2.1 to continuous integration tests (commit ecfa7431)
• Pylinted, pep8 and removed old-style exceptions from source (issue 430, issue 432)
• Use importlib for parametric imports (issue 445)
• Handle a regression introduced in Python 2.7.5 that affects XmlItemExporter (issue 372)
• Bugfix crawling shutdown on SIGINT (issue 450)
• Do not submit reset type inputs in FormRequest.from_response (commit b326b87)
• Do not silence download errors when request errback raises an exception (commit 684cfc0)
Bugfixes
Other
Thanks
• Backport scrapy check command fixes and backward compatible multi crawler process(issue 339)
• Lot of improvements to testsuite run using Tox, including a way to test on pypi
• Handle GET parameters for AJAX crawleable urls (commit 3fe2a32)
• Use lxml recover option to parse sitemaps (issue 347)
• Bugfix cookie merging by hostname and not by netloc (issue 352)
• Support disabling HttpCompressionMiddleware using a flag setting (issue 359)
• Support xml namespaces using iternodes parser in XMLFeedSpider (issue 12)
• Support dont_cache request meta flag (issue 19)
• Bugfix scrapy.utils.gz.gunzip broken by changes in python 2.7.4 (commit 4dc76e)
• Bugfix url encoding on SgmlLinkExtractor (issue 24)
• Bugfix TakeFirst processor shouldn’t discard zero (0) value (issue 59)
• Support nested items in xml exporter (issue 66)
• obey request method when scrapy deploy is redirected to a new endpoint (commit 8c4fcee)
• fix inaccurate downloader middleware documentation. refs #280 (commit 40667cb)
• doc: remove links to diveintopython.org, which is no longer available. closes #246 (commit bd58bfa)
• Find form nodes in invalid html5 documents (commit e3d6945)
• Fix typo labeling attrs type bool instead of list (commit a274276)
• Fixed error message formatting. log.err() doesn’t support cool formatting and when error occurred, the message
was: “ERROR: Error processing %(item)s” (commit c16150c)
• lint and improve images pipeline error logging (commit 56b45fc)
• fixed doc typos (commit 243be84)
• add documentation topics: Broad Crawls & Common Practies (commit 1fbb715)
• fix bug in scrapy parse command when spider is not specified explicitly. closes #209 (commit c72e682)
• Update docs/topics/commands.rst (commit 28eac7a)
• Remove concurrency limitation when using download delays and still ensure inter-request delays are enforced
(commit 487b9b5)
• add error details when image pipeline fails (commit 8232569)
• improve mac os compatibility (commit 8dcf8aa)
• setup.py: use README.rst to populate long_description (commit 7b5310d)
• doc: removed obsolete references to ClientForm (commit 80f9bb6)
• correct docs for default storage backend (commit 2aa491b)
• doc: removed broken proxyhub link from FAQ (commit bdf61c4)
• Fixed docs typo in SpiderOpenCloseLogging example (commit 7184094)
• fixed LogStats extension, which got broken after a wrong merge before the 0.16 release (commit 8c780fd)
• better backwards compatibility for scrapy.conf.settings (commit 3403089)
• extended documentation on how to access crawler stats from extensions (commit c4da0b5)
• removed .hgtags (no longer needed now that scrapy uses git) (commit d52c188)
• fix dashes under rst headers (commit fa4f7f9)
• set release date for 0.16.0 in news (commit e292246)
Scrapy changes:
• added Spiders Contracts, a mechanism for testing spiders in a formal/reproducible way
• added options -o and -t to the runspider command
• documented AutoThrottle extension and added to extensions installed by default. You still need to enable it with
AUTOTHROTTLE_ENABLED
• major Stats Collection refactoring: removed separation of global/per-spider stats, removed stats-related signals
(stats_spider_opened, etc). Stats are much simpler now, backwards compatibility is kept on the Stats
Collector API and signals.
• added process_start_requests() method to spider middlewares
• dropped Signals singleton. Signals should now be accesed through the Crawler.signals attribute. See the signals
documentation for more info.
• dropped Signals singleton. Signals should now be accesed through the Crawler.signals attribute. See the signals
documentation for more info.
• dropped Stats Collector singleton. Stats can now be accessed through the Crawler.stats attribute. See the stats
collection documentation for more info.
• documented Core API
• lxml is now the default selectors backend instead of libxml2
• ported FormRequest.from_response() to use lxml instead of ClientForm
• removed modules: scrapy.xlib.BeautifulSoup and scrapy.xlib.ClientForm
• SitemapSpider: added support for sitemap urls ending in .xml and .xml.gz, even if they advertise a wrong content
type (commit 10ed28b)
• StackTraceDump extension: also dump trackref live references (commit fe2ce93)
• nested items now fully supported in JSON and JSONLines exporters
• added cookiejar Request meta key to support multiple cookie sessions per spider
• decoupled encoding detection code to w3lib.encoding, and ported Scrapy code to use that module
• dropped support for Python 2.5. See http://blog.scrapinghub.com/2012/02/27/
scrapy-0-15-dropping-support-for-python-2-5/
• dropped support for Twisted 2.5
• added REFERER_ENABLED setting, to control referer middleware
• changed default user agent to: Scrapy/VERSION (+http://scrapy.org)
• removed (undocumented) HTMLImageLinkExtractor class from scrapy.contrib.
linkextractors.image
• removed per-spider settings (to be replaced by instantiating multiple crawler objects)
• USER_AGENT spider attribute will no longer work, use user_agent attribute instead
• DOWNLOAD_TIMEOUT spider attribute will no longer work, use download_timeout attribute instead
• removed ENCODING_ALIASES setting, as encoding auto-detection has been moved to the w3lib library
• promoted topics-djangoitem to main contrib
• LogFormatter method now return dicts(instead of strings) to support lazy formatting (issue 164, commit
dcef7b0)
• downloader handlers (DOWNLOAD_HANDLERS setting) now receive settings as the first argument of the con-
structor
• replaced memory usage acounting with (more portable) resource module, removed scrapy.utils.memory
module
• removed signal: scrapy.mail.mail_sent
• removed TRACK_REFS setting, now trackrefs is always enabled
• DBM is now the default storage backend for HTTP cache middleware
• number of log messages (per level) are now tracked through Scrapy stats (stat name: log_count/LEVEL)
• number received responses are now tracked through Scrapy stats (stat name: response_received_count)
• removed scrapy.log.started attribute
0.14.4
0.14.3
0.14.2
• move buffer pointing to start of file before computing checksum. refs #92 (commit 6a5bef2)
• Compute image checksum before persisting images. closes #92 (commit 9817df1)
0.14.1
0.14
* CONCURRENT_REQUESTS, CONCURRENT_REQUESTS_PER_DOMAIN ,
CONCURRENT_REQUESTS_PER_IP
– check the documentation for more details
• Added builtin caching DNS resolver (r2728)
• Moved Amazon AWS-related components/extensions (SQS spider queue, SimpleDB stats collector) to a sepa-
rate project: [scaws](https://github.com/scrapinghub/scaws) (r2706, r2714)
• Moved spider queues to scrapyd: scrapy.spiderqueue -> scrapyd.spiderqueue (r2708)
• Moved sqlite utils to scrapyd: scrapy.utils.sqlite -> scrapyd.sqlite (r2781)
• Real support for returning iterators on start_requests() method. The iterator is now consumed during the crawl
when the spider is getting idle (r2704)
• Added REDIRECT_ENABLED setting to quickly enable/disable the redirect middleware (r2697)
• Added RETRY_ENABLED setting to quickly enable/disable the retry middleware (r2694)
• Added CloseSpider exception to manually close spiders (r2691)
• Improved encoding detection by adding support for HTML5 meta charset declaration (r2690)
• Refactored close spider behavior to wait for all downloads to finish and be processed by spiders, before closing
the spider (r2688)
• Added SitemapSpider (see documentation in Spiders page) (r2658)
• Added LogStats extension for periodically logging basic stats (like crawled pages and scraped items) (r2657)
• Make handling of gzipped responses more robust (#319, r2643). Now Scrapy will try and decompress as much
as possible from a gzipped response, instead of failing with an IOError.
• Simplified !MemoryDebugger extension to use stats for dumping memory debugging info (r2639)
• Added new command to edit spiders: scrapy edit (r2636) and -e flag to genspider command that uses it
(r2653)
• Changed default representation of items to pretty-printed dicts. (r2631). This improves default logging by
making log more readable in the default case, for both Scraped and Dropped lines.
• Added spider_error signal (r2628)
• Added COOKIES_ENABLED setting (r2625)
• Stats are now dumped to Scrapy log (default value of STATS_DUMP setting has been changed to True). This is
to make Scrapy users more aware of Scrapy stats and the data that is collected there.
• Added support for dynamically adjusting download delay and maximum concurrent requests (r2599)
• Added new DBM HTTP cache storage backend (r2576)
• Added listjobs.json API to Scrapyd (r2571)
• CsvItemExporter: added join_multivalued parameter (r2578)
• Added namespace support to xmliter_lxml (r2552)
• Improved cookies middleware by making COOKIES_DEBUG nicer and documenting it (r2579)
• Several improvements to Scrapyd and Link extractors
• Merged item passed and item scraped concepts, as they have often proved confusing in the past. This means: (r2630)
0.12
The numbers like #NNN reference tickets in the old issue tracker (Trac) which is no longer available.
• Passed item is now sent in the item argument of the item_passed (#273)
• Added verbose option to scrapy version command, useful for bug reports (#298)
• HTTP cache now stored by default in the project data dir (#279)
• Added project data storage directory (#276, #277)
• Documented file structure of Scrapy projects (see command-line tool doc)
• New lxml backend for XPath selectors (#147)
Scrapyd changes
Changes to settings
Deprecated/obsoleted functionality
• Deprecated runserver command in favor of server command which starts a Scrapyd server. See also:
Scrapyd changes
• Deprecated queue command in favor of using Scrapyd schedule.json API. See also: Scrapyd changes
• Removed the !LxmlItemLoader (experimental contrib which never graduated to main contrib)
0.10
The numbers like #NNN reference tickets in the old issue tracker (Trac) which is no longer available.
• New Scrapy service called scrapyd for deploying Scrapy crawlers in production (#218) (documentation avail-
able)
• Simplified Images pipeline usage which doesn’t require subclassing your own images pipeline now (#217)
• Scrapy shell now shows the Scrapy log by default (#206)
• Refactored execution queue in a common base code and pluggable backends called “spider queues” (#220)
• New persistent spider queue (based on SQLite) (#198), available by default, which allows to start Scrapy in
server mode and then schedule spiders to run.
• Added documentation for Scrapy command-line tool and all its available sub-commands. (documentation avail-
able)
• New scrapy command which replaces the old scrapy-ctl.py (#199) - there is only one global scrapy command
now, instead of one scrapy-ctl.py per project - Added scrapy.bat script for running more conveniently from
Windows
• Added bash completion to command-line tool (#210)
• Renamed command start to runserver (#209)
API changes
• url and body attributes of Request objects are now read-only (#230)
• Request.copy() and Request.replace() now also copies their callback and errback attributes
(#231)
• Removed UrlFilterMiddleware from scrapy.contrib (already disabled by default)
• Offsite middelware doesn’t filter out any request coming from a spider that doesn’t have a allowed_domains
attribute (#225)
• Removed Spider Manager load() method. Now spiders are loaded in the constructor itself.
• Changes to Scrapy Manager (now called “Crawler”):
– scrapy.core.manager.ScrapyManager class renamed to scrapy.crawler.Crawler
– scrapy.core.manager.scrapymanager singleton moved to scrapy.project.
crawler
• Moved module: scrapy.contrib.spidermanager to scrapy.spidermanager
• Spider Manager singleton moved from scrapy.spider.spiders to the spiders` attribute of
``scrapy.project.crawler singleton.
• moved Stats Collector classes: (#204)
– scrapy.stats.collector.StatsCollector to scrapy.statscol.
StatsCollector
– scrapy.stats.collector.SimpledbStatsCollector to scrapy.contrib.
statscol.SimpledbStatsCollector
• default per-command settings are now specified in the default_settings attribute of command object
class (#201)
• changed arguments of Item pipeline process_item() method from (spider, item) to (item, spider)
Changes to settings
0.9
The numbers like #NNN reference tickets in the old issue tracker (Trac) which is no longer available.
API changes
0.8
The numbers like #NNN reference tickets in the old issue tracker (Trac) which is no longer available.
New features
Backwards-incompatible changes
* CLOSEDOMAIN_TIMEOUT to CLOSESPIDER_TIMEOUT
* CLOSEDOMAIN_ITEMCOUNT to CLOSESPIDER_ITEMCOUNT
• Removed deprecated SCRAPYSETTINGS_MODULE environment variable - use
SCRAPY_SETTINGS_MODULE instead (r1840)
• Renamed setting: REQUESTS_PER_DOMAIN to CONCURRENT_REQUESTS_PER_SPIDER (r1830, r1844)
• Renamed setting: CONCURRENT_DOMAINS to CONCURRENT_SPIDERS (r1830)
• Refactored HTTP Cache middleware
• HTTP Cache middleware has been heavilty refactored, retaining the same functionality except for the domain
sectorization which was removed. (r1843 )
• Renamed exception: DontCloseDomain to DontCloseSpider (r1859 | #120)
• Renamed extension: DelayedCloseDomain to SpiderCloseDelay (r1861 | #121)
• Removed obsolete scrapy.utils.markup.remove_escape_chars function - use scrapy.utils.
markup.replace_escape_chars instead (r1865)
0.7
Contributing to Scrapy
Important: Double check you are reading the most recent version of this document at http://doc.scrapy.org/en/
master/contributing.html
There are many ways to contribute to Scrapy. Here are some of them:
• Blog about Scrapy. Tell the world how you’re using Scrapy. This will help newcomers with more examples and
the Scrapy project to increase its visibility.
• Report bugs and request features in the issue tracker, trying to follow the guidelines detailed in Reporting bugs
below.
• Submit patches for new functionality and/or bug fixes. Please read Writing patches and Submitting patches
below for details on how to write and submit a patch.
• Join the scrapy-users mailing list and share your ideas on how to improve Scrapy. We’re always open to sugges-
tions.
Reporting bugs
Note: Please report security issues only to scrapy-security@googlegroups.com. This is a private list only open to
trusted Scrapy developers, and its archives are not public.
Well-written bug reports are very helpful, so keep in mind the following guidelines when reporting a new bug.
• check the FAQ first to see if your issue is addressed in a well-known question
• check the open issues to see if it has already been reported. If it has, don’t dismiss the report but check the ticket
history and comments, you may find additional useful information to contribute.
• search the scrapy-users list to see if it has been discussed there, or if you’re not sure if what you’re seeing is a
bug. You can also ask in the #scrapy IRC channel.
• write complete, reproducible, specific bug reports. The smaller the test case, the better. Remember that other
developers won’t have your project to reproduce the bug, so please include all relevant files required to reproduce
it.
• include the output of scrapy version -v so developers working on your bug know exactly which version
and platform it occurred on, which is often very helpful for reproducing it, or knowing if it was already fixed.
Writing patches
The better written a patch is, the higher chance that it’ll get accepted and the sooner that will be merged.
Well-written patches should:
• contain the minimum amount of code required for the specific change. Small patches are easier to review and
merge. So, if you’re doing more than one change (or bug fix), please consider submitting one patch per change.
Do not collapse multiple changes into a single patch. For big changes consider using a patch queue.
• pass all unit-tests. See Running tests below.
• include one (or more) test cases that check the bug fixed or the new functionality added. See Writing tests below.
• if you’re adding or changing a public (documented) API, please include the documentation changes in the same
patch. See Documentation policies below.
Submitting patches
The best way to submit a patch is to issue a pull request on Github, optionally creating a new issue first.
Remember to explain what was fixed or the new functionality (what it is, why it’s needed, etc). The more info you
include, the easier will be for core developers to understand and accept your patch.
You can also discuss the new functionality (or bug fix) before creating the patch, but it’s always good to have a patch
ready to illustrate your arguments and show that you have put some additional thought into the subject. A good starting
point is to send a pull request on Github. It can be simple enough to illustrate your idea, and leave documentation/tests
for later, after the idea has been validated and proven useful. Alternatively, you can send an email to scrapy-users to
discuss your idea first.
Finally, try to keep aesthetic changes (PEP 8 compliance, unused imports removal, etc) in separate commits than
functional changes. This will make pull requests easier to review and more likely to get merged.
Coding style
Please follow these coding conventions when writing code for inclusion in Scrapy:
• Unless otherwise specified, follow PEP 8.
• It’s OK to use lines longer than 80 chars if it improves the code readability.
• Don’t put your name in the code you contribute. Our policy is to keep the contributor’s name in the AUTHORS
file distributed with Scrapy.
Scrapy Contrib
Scrapy contrib shares a similar rationale as Django contrib, which is explained in this post. If you are working on a
new functionality, please follow that rationale to decide whether it should be a Scrapy contrib. If unsure, you can ask
in scrapy-users.
Documentation policies
• Don’t use docstrings for documenting classes, or methods which are already documented in the official (sphinx)
documentation. For example, the ItemLoader.add_value() method should be documented in the sphinx
documentation, not its docstring.
• Do use docstrings for documenting functions not present in the official (sphinx) documentation, such as func-
tions from scrapy.utils package and its sub-modules.
Tests
Tests are implemented using the Twisted unit-testing framework, running tests requires tox.
Running tests
Writing tests
All functionality (including new features and bug fixes) must include a test case to check that it works as expected, so
please include tests for your patches if you want them to get accepted sooner.
Scrapy uses unit-tests, which are located in the tests/ directory. Their module name typically resembles the full path
of the module they’re testing. For example, the item loaders code is in:
scrapy.loader
Versioning
API Stability
API stability was one of the major goals for the 1.0 release.
Methods or functions that start with a single dash (_) are private and should never be relied as stable.
Also, keep in mind that stable doesn’t mean complete: stable APIs could grow new methods or functionality but the
existing methods should keep working the same way.
s scrapy.extensions.statsmailer, 176
scrapy.contracts, 124 scrapy.http, 75
scrapy.contracts.default, 124 scrapy.item, 51
scrapy.crawler, 177 scrapy.linkextractors, 83
scrapy.downloadermiddlewares, 156 scrapy.linkextractors.lxmlhtml, 83
scrapy.downloadermiddlewares.ajaxcrawl, scrapy.loader, 55
167 scrapy.loader.processors, 62
scrapy.downloadermiddlewares.chunked, scrapy.mail, 110
164 scrapy.pipelines.files, 145
scrapy.downloadermiddlewares.cookies, scrapy.pipelines.images, 146
158 scrapy.selector, 48
scrapy.settings, 179
scrapy.downloadermiddlewares.defaultheaders,
159 scrapy.signalmanager, 182
scrapy.signals, 184
scrapy.downloadermiddlewares.downloadtimeout,
159 scrapy.spidermiddlewares, 168
scrapy.downloadermiddlewares.httpauth, scrapy.spidermiddlewares.depth, 170
159 scrapy.spidermiddlewares.httperror, 170
scrapy.downloadermiddlewares.httpcache, scrapy.spidermiddlewares.offsite, 171
160 scrapy.spidermiddlewares.referer, 171
scrapy.spidermiddlewares.urllength, 171
scrapy.downloadermiddlewares.httpcompression,
164 scrapy.spiders, 30
scrapy.downloadermiddlewares.httpproxy, scrapy.statscollectors, 110
164 scrapy.telnet, 112
scrapy.downloadermiddlewares.redirect, scrapy.utils.log, 108
164 scrapy.utils.trackref, 139
scrapy.downloadermiddlewares.retry, 165
scrapy.downloadermiddlewares.robotstxt,
166
scrapy.downloadermiddlewares.stats, 167
scrapy.downloadermiddlewares.useragent,
167
scrapy.exceptions, 101
scrapy.exporters, 187
scrapy.extensions.closespider, 175
scrapy.extensions.corestats, 174
scrapy.extensions.debug, 176
scrapy.extensions.logstats, 174
scrapy.extensions.memdebug, 175
scrapy.extensions.memusage, 174
229
Scrapy Documentation, Release 1.0.7
231
Scrapy Documentation, Release 1.0.7
view, 26 DEFAULT_ITEM_CLASS
COMMANDS_MODULE setting, 87
setting, 28 default_item_class (scrapy.loader.ItemLoader attribute),
Compose (class in scrapy.loader.processors), 63 61
COMPRESSION_ENABLED default_output_processor (scrapy.loader.ItemLoader at-
setting, 164 tribute), 61
CONCURRENT_ITEMS DEFAULT_REQUEST_HEADERS
setting, 86 setting, 87
CONCURRENT_REQUESTS default_selector_class (scrapy.loader.ItemLoader at-
setting, 87 tribute), 61
CONCURRENT_REQUESTS_PER_DOMAIN DefaultHeadersMiddleware (class in
setting, 87 scrapy.downloadermiddlewares.defaultheaders),
CONCURRENT_REQUESTS_PER_IP 159
setting, 87 delimiter (scrapy.spiders.CSVFeedSpider attribute), 37
configure_logging() (in module scrapy.utils.log), 108 DEPTH_LIMIT
connect() (scrapy.signalmanager.SignalManager setting, 87
method), 182 DEPTH_PRIORITY
context (scrapy.loader.ItemLoader attribute), 61 setting, 87
Contract (class in scrapy.contracts), 124 DEPTH_STATS
cookiejar setting, 88
reqmeta, 158 DEPTH_STATS_VERBOSE
COOKIES_DEBUG setting, 88
setting, 159 DepthMiddleware (class in
COOKIES_ENABLED scrapy.spidermiddlewares.depth), 170
setting, 158 disconnect() (scrapy.signalmanager.SignalManager
CookiesMiddleware (class in method), 182
scrapy.downloadermiddlewares.cookies), disconnect_all() (scrapy.signalmanager.SignalManager
158 method), 183
copy() (scrapy.http.Request method), 76 DNS_TIMEOUT
copy() (scrapy.http.Response method), 81 setting, 88
copy() (scrapy.settings.Settings method), 181 DNSCACHE_ENABLED
CoreStats (class in scrapy.extensions.corestats), 174 setting, 88
crawl DNSCACHE_SIZE
command, 24 setting, 88
crawl() (scrapy.crawler.Crawler method), 178 dont_cache
crawl() (scrapy.crawler.CrawlerProcess method), 178 reqmeta, 160
crawl() (scrapy.crawler.CrawlerRunner method), 178 dont_obey_robotstxt
Crawler (class in scrapy.crawler), 177 reqmeta, 167
crawler (scrapy.spiders.Spider attribute), 30 dont_redirect
CrawlerProcess (class in scrapy.crawler), 178 reqmeta, 164
CrawlerRunner (class in scrapy.crawler), 178 dont_retry
crawlers (scrapy.crawler.CrawlerProcess attribute), 179 reqmeta, 166
crawlers (scrapy.crawler.CrawlerRunner attribute), 178DOWNLOAD_DELAY
CrawlSpider (class in scrapy.spiders), 33 setting, 89
css() (scrapy.http.TextResponse method), 82 DOWNLOAD_HANDLERS
css() (scrapy.selector.Selector method), 49 setting, 89
css() (scrapy.selector.SelectorList method), 49 DOWNLOAD_HANDLERS_BASE
CSVFeedSpider (class in scrapy.spiders), 37 setting, 89
CsvItemExporter (class in scrapy.exporters), 190 DOWNLOAD_MAXSIZE
custom_settings (scrapy.spiders.Spider attribute), 30 setting, 90
download_maxsize
D reqmeta, 90
default_input_processor (scrapy.loader.ItemLoader at- DOWNLOAD_TIMEOUT
tribute), 61 setting, 90
232 Index
Scrapy Documentation, Release 1.0.7
download_timeout F
reqmeta, 78 FEED_EXPORT_FIELDS
DOWNLOAD_WARNSIZE setting, 73
setting, 90 FEED_EXPORTERS
DOWNLOADER setting, 74
setting, 88 FEED_EXPORTERS_BASE
DOWNLOADER_MIDDLEWARES setting, 74
setting, 88 FEED_FORMAT
DOWNLOADER_MIDDLEWARES_BASE setting, 73
setting, 88 FEED_STORAGES
DOWNLOADER_STATS setting, 74
setting, 89 FEED_STORAGES_BASE
DownloaderMiddleware (class in setting, 74
scrapy.downloadermiddlewares), 156 FEED_STORE_EMPTY
DownloaderStats (class in setting, 74
scrapy.downloadermiddlewares.stats), 167 FEED_URI
DownloadTimeoutMiddleware (class in setting, 73
scrapy.downloadermiddlewares.downloadtimeout),fetch
159 command, 26
DropItem, 101 Field (class in scrapy.item), 54
DummyStatsCollector (class in scrapy.statscollectors), fields (scrapy.item.Item attribute), 54
110 fields_to_export (scrapy.exporters.BaseItemExporter at-
DUPEFILTER_CLASS tribute), 189
setting, 91 FILES_EXPIRES
DUPEFILTER_DEBUG setting, 144
setting, 91 FILES_STORE
setting, 142
E FilesPipeline (class in scrapy.pipelines.files), 145
edit find_by_request() (scrapy.loader.SpiderLoader method),
command, 25 182
EDITOR finish_exporting() (scrapy.exporters.BaseItemExporter
setting, 91 method), 189
encoding (scrapy.exporters.BaseItemExporter attribute), flags (scrapy.http.Response attribute), 81
189 FormRequest (class in scrapy.http), 78
encoding (scrapy.http.TextResponse attribute), 81 freeze() (scrapy.settings.Settings method), 181
engine (scrapy.crawler.Crawler attribute), 177 from_crawler(), 68
engine_started from_crawler() (scrapy.spiders.Spider method), 30
signal, 184 from_response() (scrapy.http.FormRequest class
engine_started() (in module scrapy.signals), 184 method), 78
engine_stopped from_settings() (scrapy.loader.SpiderLoader method),
signal, 184 182
engine_stopped() (in module scrapy.signals), 184 from_settings() (scrapy.mail.MailSender class method),
export_empty_fields (scrapy.exporters.BaseItemExporter 111
attribute), 189 frozencopy() (scrapy.settings.Settings method), 181
export_item() (scrapy.exporters.BaseItemExporter
method), 189 G
EXTENSIONS genspider
setting, 91 command, 24
extensions (scrapy.crawler.Crawler attribute), 177 get() (scrapy.settings.Settings method), 180
EXTENSIONS_BASE get_collected_values() (scrapy.loader.ItemLoader
setting, 91 method), 60
extract() (scrapy.selector.Selector method), 49 get_css() (scrapy.loader.ItemLoader method), 60
extract() (scrapy.selector.SelectorList method), 49 get_input_processor() (scrapy.loader.ItemLoader
method), 60
Index 233
Scrapy Documentation, Release 1.0.7
234 Index
Scrapy Documentation, Release 1.0.7
J MEMDEBUG_ENABLED
Join (class in scrapy.loader.processors), 62 setting, 93
join() (scrapy.crawler.CrawlerProcess method), 179 MEMDEBUG_NOTIFY
join() (scrapy.crawler.CrawlerRunner method), 178 setting, 93
JsonItemExporter (class in scrapy.exporters), 192 MemoryStatsCollector (class in scrapy.statscollectors),
JsonLinesItemExporter (class in scrapy.exporters), 192 110
MEMUSAGE_ENABLED
L setting, 93
list MEMUSAGE_LIMIT_MB
command, 25 setting, 93
list() (scrapy.loader.SpiderLoader method), 182 MEMUSAGE_NOTIFY_MAIL
load() (scrapy.loader.SpiderLoader method), 182 setting, 94
load_item() (scrapy.loader.ItemLoader method), 60 MEMUSAGE_REPORT
log() (scrapy.spiders.Spider method), 31 setting, 94
LOG_DATEFORMAT MEMUSAGE_WARNING_MB
setting, 92 setting, 94
LOG_ENABLED meta (scrapy.http.Request attribute), 76
setting, 92 meta (scrapy.http.Response attribute), 81
LOG_ENCODING METAREFRESH_ENABLED
setting, 92 setting, 165
LOG_FILE MetaRefreshMiddleware (class in
setting, 92 scrapy.downloadermiddlewares.redirect),
LOG_FORMAT 165
setting, 92 method (scrapy.http.Request attribute), 76
LOG_LEVEL min_value() (scrapy.statscollectors.StatsCollector
setting, 93 method), 183
LOG_STDOUT
setting, 93
N
logger (scrapy.spiders.Spider attribute), 30 name (scrapy.spiders.Spider attribute), 30
LogStats (class in scrapy.extensions.logstats), 174 namespaces (scrapy.spiders.XMLFeedSpider attribute),
LxmlLinkExtractor (class in 35
scrapy.linkextractors.lxmlhtml), 83 NEWSPIDER_MODULE
setting, 94
M NotConfigured, 102
MAIL_FROM NotSupported, 102
setting, 111
MAIL_HOST O
setting, 111 object_ref (class in scrapy.utils.trackref), 139
MAIL_PASS OffsiteMiddleware (class in
setting, 112 scrapy.spidermiddlewares.offsite), 171
MAIL_PORT open_spider(), 68
setting, 111 open_spider() (scrapy.statscollectors.StatsCollector
MAIL_SSL method), 183
setting, 112
MAIL_TLS P
setting, 112 parse
MAIL_USER command, 27
setting, 112 parse() (scrapy.spiders.Spider method), 31
MailSender (class in scrapy.mail), 110 parse_node() (scrapy.spiders.XMLFeedSpider method),
make_requests_from_url() (scrapy.spiders.Spider 36
method), 31 parse_row() (scrapy.spiders.CSVFeedSpider method), 37
MapCompose (class in scrapy.loader.processors), 63 parse_start_url() (scrapy.spiders.CrawlSpider method),
max_value() (scrapy.statscollectors.StatsCollector 34
method), 183 PickleItemExporter (class in scrapy.exporters), 191
Index 235
Scrapy Documentation, Release 1.0.7
236 Index
Scrapy Documentation, Release 1.0.7
Index 237
Scrapy Documentation, Release 1.0.7
238 Index
Scrapy Documentation, Release 1.0.7
URLLENGTH_LIMIT, 97 SPIDER_MIDDLEWARES_BASE
USER_AGENT, 97 setting, 96
settings SPIDER_MODULES
command, 27 setting, 96
Settings (class in scrapy.settings), 179 spider_opened
settings (scrapy.crawler.Crawler attribute), 177 signal, 185
settings (scrapy.spiders.Spider attribute), 30 spider_opened() (in module scrapy.signals), 185
SETTINGS_PRIORITIES (in module scrapy.settings), spider_stats (scrapy.statscollectors.MemoryStatsCollector
179 attribute), 110
shell SpiderLoader (class in scrapy.loader), 182
command, 26 SpiderMiddleware (class in scrapy.spidermiddlewares),
signal 168
engine_started, 184 start() (scrapy.crawler.CrawlerProcess method), 179
engine_stopped, 184 start_exporting() (scrapy.exporters.BaseItemExporter
item_dropped, 184 method), 189
item_scraped, 184 start_requests() (scrapy.spiders.Spider method), 31
request_dropped, 186 start_urls (scrapy.spiders.Spider attribute), 30
request_scheduled, 186 startproject
response_downloaded, 186 command, 24
response_received, 186 stats (scrapy.crawler.Crawler attribute), 177
spider_closed, 185 STATS_CLASS
spider_error, 185 setting, 97
spider_idle, 185 STATS_DUMP
spider_opened, 185 setting, 97
update_telnet_vars, 114 StatsCollector (class in scrapy.statscollectors), 183
SignalManager (class in scrapy.signalmanager), 182 STATSMAILER_RCPTS
signals (scrapy.crawler.Crawler attribute), 177 setting, 97
sitemap_alternate_links (scrapy.spiders.SitemapSpider status (scrapy.http.Response attribute), 80
attribute), 38 stop() (scrapy.crawler.CrawlerProcess method), 179
sitemap_follow (scrapy.spiders.SitemapSpider attribute), stop() (scrapy.crawler.CrawlerRunner method), 178
38
sitemap_rules (scrapy.spiders.SitemapSpider attribute), T
37 TakeFirst (class in scrapy.loader.processors), 62
sitemap_urls (scrapy.spiders.SitemapSpider attribute), 37 TELNETCONSOLE_ENABLED
SitemapSpider (class in scrapy.spiders), 37 setting, 97
Spider (class in scrapy.spiders), 30 TELNETCONSOLE_HOST
spider (scrapy.crawler.Crawler attribute), 177 setting, 114
spider_closed TELNETCONSOLE_PORT
signal, 185 setting, 97, 114
spider_closed() (in module scrapy.signals), 185 TEMPLATES_DIR
SPIDER_CONTRACTS setting, 97
setting, 95 TextResponse (class in scrapy.http), 81
SPIDER_CONTRACTS_BASE
setting, 96 U
spider_error update_telnet_vars
signal, 185 signal, 114
spider_error() (in module scrapy.signals), 185 update_telnet_vars() (in module scrapy.telnet), 114
spider_idle url (scrapy.http.Request attribute), 76
signal, 185 url (scrapy.http.Response attribute), 80
spider_idle() (in module scrapy.signals), 185 UrlContract (class in scrapy.contracts.default), 124
SPIDER_LOADER_CLASS urljoin() (scrapy.http.Response method), 81
setting, 96 URLLENGTH_LIMIT
SPIDER_MIDDLEWARES setting, 97
setting, 96
Index 239
Scrapy Documentation, Release 1.0.7
UrlLengthMiddleware (class in
scrapy.spidermiddlewares.urllength), 171
USER_AGENT
setting, 97
UserAgentMiddleware (class in
scrapy.downloadermiddlewares.useragent),
167
V
version
command, 28
view
command, 26
X
XMLFeedSpider (class in scrapy.spiders), 35
XmlItemExporter (class in scrapy.exporters), 190
XmlResponse (class in scrapy.http), 82
xpath() (scrapy.http.TextResponse method), 82
xpath() (scrapy.selector.Selector method), 48
xpath() (scrapy.selector.SelectorList method), 49
240 Index