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 Dive Into Python. 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 set up a new Scrapy project. Enter a directory where you’d like to store your code and then run:

scrapy startproject dmoz

This will create a dmoz directory with the following contents:


These are basically:

  • scrapy.cfg: the project configuration file
  • dmoz/: the project’s python module, you’ll later import your code from here.
  • dmoz/ the project’s items file.
  • dmoz/ the project’s pipelines file.
  • dmoz/ the project’s settings file.
  • dmoz/spiders/: a directory where you’ll later put your spiders.

Defining our Item

Items are containers that will be loaded with the scraped data; they work like simple python dicts but they offer some additional features like providing default values.

They are declared by creating an scrapy.item.Item class an defining its attributes as scrapy.item.Field objects, like you will 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 sites data obtained from, 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, found in the dmoz directory. Our Item class looks like this:

# Define here the models for your scraped items

from scrapy.item import Item, Field

class DmozItem(Item):
    title = Field()
    link = Field()
    desc = Field()

This may seem complicated at first, but defining the item allows you to use other handy components of Scrapy that need to know how your item looks like.

Our first Spider

Spiders are user-written classes used 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 those pages to extract items.

To create a Spider, you must subclass scrapy.spider.BaseSpider, and define the three main, mandatory, attributes:

  • name: identifies the Spider. It must be unique, that is, you can’t set the same name for different Spiders.

  • start_urls: is a list of URLs where the Spider will begin to crawl from. So, the first pages downloaded will be those listed here. The subsequent URLs will be generated successively from data contained in the start URLs.

  • parse() is 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 under the dmoz/spiders directory:

from scrapy.spider import BaseSpider

class DmozSpider(BaseSpider):
    name = ""
    allowed_domains = [""]
    start_urls = [

    def parse(self, response):
        filename = response.url.split("/")[-2]
        open(filename, 'wb').write(response.body)


To put our spider to work, go to the project’s top level directory and run:

scrapy crawl

The crawl command runs the spider for the domain. You will get an output similar to this:

2008-08-20 03:51:13-0300 [scrapy] INFO: Started project: dmoz
2008-08-20 03:51:13-0300 [dmoz] INFO: Enabled extensions: ...
2008-08-20 03:51:13-0300 [dmoz] INFO: Enabled scheduler middlewares: ...
2008-08-20 03:51:13-0300 [dmoz] INFO: Enabled downloader middlewares: ...
2008-08-20 03:51:13-0300 [dmoz] INFO: Enabled spider middlewares: ...
2008-08-20 03:51:13-0300 [dmoz] INFO: Enabled item pipelines: ...
2008-08-20 03:51:14-0300 [] INFO: Spider opened
2008-08-20 03:51:14-0300 [] DEBUG: Crawled <> from <None>
2008-08-20 03:51:14-0300 [] DEBUG: Crawled <> from <None>
2008-08-20 03:51:14-0300 [] INFO: Spider closed (finished)

Pay attention to the lines containing [], which corresponds to our spider (identified by the domain ""). 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 from <None>.

But more interesting, as our parse method instructs, two files have been created: Books and Resources, with the content of both URLs.

What just happened under the hood?

Scrapy creates scrapy.http.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 expressions called XPath selectors. For more information about selectors and other extraction mechanisms see the XPath selectors documentation.

Here are some examples of XPath expressions and their meanings:

  • /html/head/title: selects the <title> element, inside the <head> element of a 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 XPath tutorial.

For working with XPaths, Scrapy provides a XPathSelector class, which comes in two flavours, HtmlXPathSelector (for HTML data) and XmlXPathSelector (for XML data). In order to use them you must instantiate the desired class with a Response object.

You can see selectors as objects that represent nodes in the document structure. So, the first instantiated selectors are associated to the root node, or the entire document.

Selectors have three methods (click on the method to see the complete API documentation).

  • select(): returns a list of selectors, each of them representing the nodes selected by the xpath expression given as argument.

  • extract(): returns a unicode string with

    the data selected by the XPath selector.

  • re(): returns a list of unicode strings extracted by applying the regular expression given as argument.

Trying Selectors in the Shell

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:

scrapy shell

This is what the shell looks like:

[ ... Scrapy log here ... ]

[s] Available Scrapy objects:
[s] 2010-08-19 21:45:59-0300 [default] INFO: Spider closed (finished)
[s]   hxs        <HtmlXPathSelector ( xpath=None>
[s]   item       Item()
[s]   request    <GET>
[s]   response   <200>
[s]   spider     <BaseSpider 'default' at 0x1b6c2d0>
[s]   xxs        <XmlXPathSelector ( xpath=None>
[s] Useful shortcuts:
[s]   shelp()           Print this help
[s]   fetch(req_or_url) Fetch a new request or URL and update shell objects
[s]   view(response)    View response in a browser

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.

The shell also instantiates two selectors, one for HTML (in the hxs variable) and one for XML (in the xxs variable) with this response. So let’s try them:

In [1]:'/html/head/title')
Out[1]: [<HtmlXPathSelector (title) xpath=/html/head/title>]

In [2]:'/html/head/title').extract()
Out[2]: [u'<title>Open Directory - Computers: Programming: Languages: Python: Books</title>']

In [3]:'/html/head/title/text()')
Out[3]: [<HtmlXPathSelector (text) xpath=/html/head/title/text()>]

In [4]:'/html/head/title/text()').extract()
Out[4]: [u'Open Directory - Computers: Programming: Languages: Python: Books']

In [5]:'/html/head/title/text()').re('(\w+):')
Out[5]: [u'Computers', u'Programming', u'Languages', u'Python']

Extracting the data

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 this an easier task, you can use 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 sites information is inside a <ul> element, in fact the second <ul> element.

So we can select each <li> element belonging to the sites list with this code:'//ul[2]/li')

And from them, the sites descriptions:'//ul[2]/li/text()').extract()

The sites titles:'//ul[2]/li/a/text()').extract()

And the sites links:'//ul[2]/li/a/@href').extract()

As we said before, each select() call returns a list of selectors, so we can concatenate further select() calls to dig deeper into a node. We are going to use that property here, so:

sites ='//ul[2]/li')
for site in sites:
    title ='a/text()').extract()
    link ='a/@href').extract()
    desc ='text()').extract()
    print title, link, desc


For a more detailed description of using nested selectors, see Nesting selectors and Working with relative XPaths in the XPath Selectors documentation

Let’s add this code to our spider:

from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector

class DmozSpider(BaseSpider):
   name = ""
   allowed_domains = [""]
   start_urls = [

   def parse(self, response):
       hxs = HtmlXPathSelector(response)
       sites ='//ul[2]/li')
       for site in sites:
           title ='a/text()').extract()
           link ='a/@href').extract()
           desc ='text()').extract()
           print title, link, desc

Now try crawling the domain again and you’ll see sites being printed in your output, run:

scrapy crawl

Using our item

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'

Spiders are expected to return their scraped data inside Item objects, so to actually return the data we’ve scraped so far, the code for our Spider should be like this:

from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector

from dmoz.items import DmozItem

class DmozSpider(BaseSpider):
   name = ""
   allowed_domains = [""]
   start_urls = [

   def parse(self, response):
       hxs = HtmlXPathSelector(response)
       sites ='//ul[2]/li')
       items = []
       for site in sites:
           item = DmozItem()
           item['title'] ='a/text()').extract()
           item['link'] ='a/@href').extract()
           item['desc'] ='text()').extract()
       return items

Now doing a crawl on the domain yields DmozItem‘s:

[] DEBUG: Scraped DmozItem(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''], title=[u'Text Processing in Python']) in <>
[] DEBUG: Scraped DmozItem(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 Pyxie open source XML processing library. [Prentice Hall PTR]\n'], link=[u''], title=[u'XML Processing with Python']) in <>

Storing the data (using an Item Pipeline)

After an item has been scraped by a Spider, it is sent to the Item Pipeline.

The Item Pipeline is a group of user written Python classes that implement a simple method. They receive an Item and perform an action over it (for example: validation, checking for duplicates, or storing it in a database), and then decide if the Item continues through the Pipeline or it’s dropped and no longer processed.

In small projects (like the one on this tutorial), we will use only one Item Pipeline that just stores our Items.

As with Items, a Pipeline placeholder has been set up for you in the project creation step, it’s in dmoz/ and looks like this:

# Define your item pipelines here

class DmozPipeline(object):
    def process_item(self, item, spider):
        return item

We have to override the process_item method in order to store our Items somewhere.

Here’s a simple pipeline for storing the scraped items into a CSV (comma separated values) file using the standard library csv module:

import csv

class CsvWriterPipeline(object):

    def __init__(self):
        self.csvwriter = csv.writer(open('items.csv', 'wb'))

    def process_item(self, item, spider):
        self.csvwriter.writerow([item['title'][0], item['link'][0], item['desc'][0]])
        return item

Don’t forget to enable the pipeline by adding it to the ITEM_PIPELINES setting in your, like this:

ITEM_PIPELINES = ['dmoz.pipelines.CsvWriterPipeline']


This tutorial covers only the basics of Scrapy, but there’s a lot of other features not mentioned here. We recommend you continue reading the section Scrapy documentation.