Spiders

Spiders are classes which define how a certain site (or a group of sites) will bescraped, including how to perform the crawl (i.e. follow links) and how toextract structured data from their pages (i.e. scraping items). In other words,Spiders are the place where you define the custom behaviour for crawling andparsing pages for a particular site (or, in some cases, a group of sites).

For spiders, the scraping cycle goes through something like this:

  • You start by generating the initial Requests to crawl the first URLs, andspecify a callback function to be called with the response downloaded fromthose requests.

The first requests to perform are obtained by calling thestart_requests() method which (by default)generates Request for the URLs specified in thestart_urls and theparse method as callback function for theRequests.

  • In the callback function, you parse the response (web page) and return eitherdicts with extracted data, Item objects,Request objects, or an iterable of these objects.Those Requests will also contain a callback (maybethe same) and will then be downloaded by Scrapy and then theirresponse handled by the specified callback.

  • In callback functions, you parse the page contents, typically usingSelectors (but you can also use BeautifulSoup, lxml or whatevermechanism you prefer) and generate items with the parsed data.

  • Finally, the items returned from the spider will be typically persisted to adatabase (in some Item Pipeline) or written toa file using Feed exports.

Even though this cycle applies (more or less) to any kind of spider, there aredifferent kinds of default spiders bundled into Scrapy for different purposes.We will talk about those types here.

scrapy.Spider

  • class scrapy.spiders.Spider[source]
  • This is the simplest spider, and the one from which every other spidermust inherit (including spiders that come bundled with Scrapy, as well as spidersthat you write yourself). It doesn’t provide any special functionality. It justprovides a default start_requests() implementation which sends requests fromthe start_urls spider attribute and calls the spider’s method parsefor each of the resulting responses.

    • name
    • A string which defines the name for this spider. The spider name is howthe spider is located (and instantiated) by Scrapy, so it must beunique. However, nothing prevents you from instantiating more than oneinstance of the same spider. This is the most important spider attributeand it’s required.

If the spider scrapes a single domain, a common practice is to name thespider after the domain, with or without the TLD. So, for example, aspider that crawls mywebsite.com would often be calledmywebsite.

  • allowed_domains
  • An optional list of strings containing domains that this spider isallowed to crawl. Requests for URLs not belonging to the domain namesspecified in this list (or their subdomains) won’t be followed ifOffsiteMiddleware is enabled.

Let’s say your target url is https://www.example.com/1.html,then add 'example.com' to the list.

  • start_urls
  • A list of URLs where the spider will begin to crawl from, when noparticular URLs are specified. So, the first pages downloaded will be thoselisted here. The subsequent Request will be generated successively from datacontained in the start URLs.

  • custom_settings

  • A dictionary of settings that will be overridden from the project wideconfiguration when running this spider. It must be defined as a classattribute 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 afterinitializating the class, and links to theCrawler object to which this spider instance isbound.

Crawlers encapsulate a lot of components in the project for their singleentry access (such as extensions, middlewares, signals managers, etc).See Crawler API to know more about them.

  • settings
  • Configuration for running this spider. This is aSettings instance, see theSettings topic for a detailed introduction on this subject.

  • logger

  • Python logger created with the Spider’s name. You can use it tosend log messages through it as described onLogging from Spiders.

  • fromcrawler(_crawler, *args, **kwargs)[source]

  • This is the class method used by Scrapy to create your spiders.

You probably won’t need to override this directly because the defaultimplementation acts as a proxy to the init() method, callingit with the given arguments args and named arguments kwargs.

Nonetheless, this method sets the crawler and settingsattributes in the new instance so they can be accessed later inside thespider’s code.

Parameters:

  1. - **crawler** ([<code>Crawler</code>]($ceb8c09efd04cb82.md#scrapy.crawler.Crawler) instance) – crawler to which the spider will be bound
  2. - **args** ([_list_](https://docs.python.org/3/library/stdtypes.html#list)) – arguments passed to the <code>__init__()</code> method
  3. - **kwargs** ([_dict_](https://docs.python.org/3/library/stdtypes.html#dict)) – keyword arguments passed to the <code>__init__()</code> method
  • start_requests()[source]
  • This method must return an iterable with the first Requests to crawl forthis spider. It is called by Scrapy when the spider is opened forscraping. Scrapy calls it only once, so it is safe to implementstart_requests() as a generator.

The default implementation generates Request(url, dont_filter=True)for each url in start_urls.

If you want to change the Requests used to start scraping a domain, this isthe method to override. For example, if you need to start by logging in usinga POST request, you could do:

  1. class MySpider(scrapy.Spider):
  2. name = 'myspider'
  3.  
  4. def start_requests(self):
  5. return [scrapy.FormRequest("http://www.example.com/login",
  6. formdata={'user': 'john', 'pass': 'secret'},
  7. callback=self.logged_in)]
  8.  
  9. def logged_in(self, response):
  10. # here you would extract links to follow and return Requests for
  11. # each of them, with another callback
  12. pass
  • parse(response)[source]
  • This is the default callback used by Scrapy to process downloadedresponses, when their requests don’t specify a callback.

The parse method is in charge of processing the response and returningscraped data and/or more URLs to follow. Other Requests callbacks havethe same requirements as the Spider class.

This method, as well as any other Request callback, must return aniterable of Request and/ordicts or Item objects.

Parameters:response (Response) – the response to parse

  • log(message[, level, component])[source]
  • Wrapper that sends a log message through the Spider’s logger,kept for backward compatibility. For more information seeLogging from Spiders.

  • closed(reason)

  • Called when the spider closes. This method provides a shortcut tosignals.connect() for the spider_closed signal.

Let’s see an example:

  1. import scrapy
  2.  
  3.  
  4. class MySpider(scrapy.Spider):
  5. name = 'example.com'
  6. allowed_domains = ['example.com']
  7. start_urls = [
  8. 'http://www.example.com/1.html',
  9. 'http://www.example.com/2.html',
  10. 'http://www.example.com/3.html',
  11. ]
  12.  
  13. def parse(self, response):
  14. self.logger.info('A response from %s just arrived!', response.url)

Return multiple Requests and items from a single callback:

  1. import scrapy
  2.  
  3. class MySpider(scrapy.Spider):
  4. name = 'example.com'
  5. allowed_domains = ['example.com']
  6. start_urls = [
  7. 'http://www.example.com/1.html',
  8. 'http://www.example.com/2.html',
  9. 'http://www.example.com/3.html',
  10. ]
  11.  
  12. def parse(self, response):
  13. for h3 in response.xpath('//h3').getall():
  14. yield {"title": h3}
  15.  
  16. for href in response.xpath('//a/@href').getall():
  17. yield scrapy.Request(response.urljoin(href), self.parse)

Instead of start_urls you can use start_requests() directly;to give data more structure you can use Items:

  1. import scrapy
  2. from myproject.items import MyItem
  3.  
  4. class MySpider(scrapy.Spider):
  5. name = 'example.com'
  6. allowed_domains = ['example.com']
  7.  
  8. def start_requests(self):
  9. yield scrapy.Request('http://www.example.com/1.html', self.parse)
  10. yield scrapy.Request('http://www.example.com/2.html', self.parse)
  11. yield scrapy.Request('http://www.example.com/3.html', self.parse)
  12.  
  13. def parse(self, response):
  14. for h3 in response.xpath('//h3').getall():
  15. yield MyItem(title=h3)
  16.  
  17. for href in response.xpath('//a/@href').getall():
  18. yield scrapy.Request(response.urljoin(href), self.parse)

Spider arguments

Spiders can receive arguments that modify their behaviour. Some common uses forspider arguments are to define the start URLs or to restrict the crawl tocertain sections of the site, but they can be used to configure anyfunctionality of the spider.

Spider arguments are passed through the crawl command using the-a option. For example:

  1. scrapy crawl myspider -a category=electronics

Spiders can access arguments in their init methods:

  1. import scrapy
  2.  
  3. class MySpider(scrapy.Spider):
  4. name = 'myspider'
  5.  
  6. def __init__(self, category=None, *args, **kwargs):
  7. super(MySpider, self).__init__(*args, **kwargs)
  8. self.start_urls = ['http://www.example.com/categories/%s' % category]
  9. # ...

The default init method will take any spider argumentsand copy them to the spider as attributes.The above example can also be written as follows:

  1. import scrapy
  2.  
  3. class MySpider(scrapy.Spider):
  4. name = 'myspider'
  5.  
  6. def start_requests(self):
  7. yield scrapy.Request('http://www.example.com/categories/%s' % self.category)

Keep in mind that spider arguments are only strings.The spider will not do any parsing on its own.If you were to set the start_urls attribute from the command line,you would have to parse it on your own into a listusing something likeast.literal_evalor json.loadsand then set it as an attribute.Otherwise, you would cause iteration over a start_urls string(a very common python pitfall)resulting in each character being seen as a separate url.

A valid use case is to set the http auth credentialsused by HttpAuthMiddlewareor the user agentused by UserAgentMiddleware:

  1. scrapy crawl myspider -a http_user=myuser -a http_pass=mypassword -a user_agent=mybot

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 subclassyour spiders from. Their aim is to provide convenient functionality for a fewcommon scraping cases, like following all links on a site based on certainrules, crawling from Sitemaps, or parsing an XML/CSV feed.

For the examples used in the following spiders, we’ll assume you have a projectwith a TestItem declared in a myproject.items module:

  1. import scrapy
  2.  
  3. class TestItem(scrapy.Item):
  4. id = scrapy.Field()
  5. name = scrapy.Field()
  6. description = scrapy.Field()

CrawlSpider

  • class scrapy.spiders.CrawlSpider[source]
  • This is the most commonly used spider for crawling regular websites, as itprovides 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, butit’s generic enough for several cases, so you can start from it and override itas needed for more custom functionality, or just implement your own spider.

Apart from the attributes inherited from Spider (that you mustspecify), this class supports a new attribute:

  • rules
  • Which is a list of one (or more) Rule objects. Each Ruledefines a certain behaviour for crawling the site. Rules objects aredescribed below. If multiple rules match the same link, the first onewill be used, according to the order they’re defined in this attribute.

This spider also exposes an overrideable method:

  • parsestart_url(_response)[source]
  • This method is called for the start_urls responses. It allows to parsethe initial responses and must return either anItem object, a Requestobject, or an iterable containing any of them.

Crawling rules

  • class scrapy.spiders.Rule(link_extractor=None, callback=None, cb_kwargs=None, follow=None, process_links=None, process_request=None, errback=None)[source]
  • link_extractor is a Link Extractor object whichdefines how links will be extracted from each crawled page. Each produced link willbe used to generate a Request object, which will contain thelink’s text in its meta dictionary (under the link_text key).If omitted, a default link extractor created with no arguments will be used,resulting in all links being extracted.

callback is a callable or a string (in which case a method from the spiderobject with that name will be used) to be called for each link extracted withthe specified link extractor. This callback receives a Responseas its first argument and must return either a single instance or an iterable ofItem, dict and/or Request objects(or any subclass of them). As mentioned above, the received Responseobject will contain the text of the link that produced the Requestin its meta dictionary (under the link_text key)

Warning

When writing crawl spider rules, avoid using parse ascallback, since the CrawlSpider uses the parse methoditself 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 thecallback function.

follow is a boolean which specifies if links should be followed from eachresponse extracted with this rule. If callback is None follow defaultsto True, otherwise it defaults to False.

process_links is a callable, or a string (in which case a method from thespider object with that name will be used) which will be called for each listof 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 fromthe spider object with that name will be used) which will be called for everyRequest extracted by this rule. This callable shouldtake said request as first argument and the Responsefrom which the request originated as second argument. It must return aRequest object or None (to filter out the request).

errback is a callable or a string (in which case a method from the spiderobject with that name will be used) to be called if any exception israised while processing a request generated by the rule.It receives a Twisted Failureinstance as first parameter.

New in version 2.0: The errback parameter.

CrawlSpider example

Let’s now take a look at an example CrawlSpider with rules:

  1. import scrapy
  2. from scrapy.spiders import CrawlSpider, Rule
  3. from scrapy.linkextractors import LinkExtractor
  4.  
  5. class MySpider(CrawlSpider):
  6. name = 'example.com'
  7. allowed_domains = ['example.com']
  8. start_urls = ['http://www.example.com']
  9.  
  10. rules = (
  11. # Extract links matching 'category.php' (but not matching 'subsection.php')
  12. # and follow links from them (since no callback means follow=True by default).
  13. Rule(LinkExtractor(allow=('category\.php', ), deny=('subsection\.php', ))),
  14.  
  15. # Extract links matching 'item.php' and parse them with the spider's method parse_item
  16. Rule(LinkExtractor(allow=('item\.php', )), callback='parse_item'),
  17. )
  18.  
  19. def parse_item(self, response):
  20. self.logger.info('Hi, this is an item page! %s', response.url)
  21. item = scrapy.Item()
  22. item['id'] = response.xpath('//td[@id="item_id"]/text()').re(r'ID: (\d+)')
  23. item['name'] = response.xpath('//td[@id="item_name"]/text()').get()
  24. item['description'] = response.xpath('//td[@id="item_description"]/text()').get()
  25. item['link_text'] = response.meta['link_text']
  26. return item

This spider would start crawling example.com’s home page, collecting categorylinks, and item links, parsing the latter with the parse_item method. Foreach item response, some data will be extracted from the HTML using XPath, andan Item will be filled with it.

XMLFeedSpider

  • class scrapy.spiders.XMLFeedSpider[source]
  • XMLFeedSpider is designed for parsing XML feeds by iterating through them by acertain node name. The iterator can be chosen from: iternodes, xml,and html. It’s recommended to use the iternodes iterator forperformance reasons, since the xml and html iterators generate thewhole DOM at once in order to parse it. However, using html as theiterator may be useful when parsing XML with bad markup.

To set the iterator and the tag name, you must define the following classattributes:

  • 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 memorywhich 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 memorywhich 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:
  1. itertag = 'product'
  • namespaces
  • A list of (prefix, uri) tuples which define the namespacesavailable in that document that will be processed with this spider. Theprefix and uri will be used to automatically registernamespaces using theregister_namespace() method.

You can then specify nodes with namespaces in the itertagattribute.

Example:

  1. class YourSpider(XMLFeedSpider):
  2.  
  3. namespaces = [('n', 'http://www.sitemaps.org/schemas/sitemap/0.9')]
  4. itertag = 'n:url'
  5. # ...

Apart from these new attributes, this spider has the following overrideablemethods too:

  • adaptresponse(_response)[source]
  • A method that receives the response as soon as it arrives from the spidermiddleware, before the spider starts parsing it. It can be used to modifythe response body before parsing it. This method receives a response andalso returns a response (it could be the same or another one).

  • parsenode(_response, selector)[source]

  • This method is called for the nodes matching the provided tag name(itertag). Receives the response and anSelector for each node. Overriding thismethod is mandatory. Otherwise, you spider won’t work. This methodmust return either a Item object, aRequest object, or an iterable containing any ofthem.

  • processresults(_response, results)[source]

  • This method is called for each result (item or request) returned by thespider, and it’s intended to perform any last time processing requiredbefore returning the results to the framework core, for example setting theitem IDs. It receives a list of results and the response which originatedthose 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:

  1. from scrapy.spiders import XMLFeedSpider
  2. from myproject.items import TestItem
  3.  
  4. class MySpider(XMLFeedSpider):
  5. name = 'example.com'
  6. allowed_domains = ['example.com']
  7. start_urls = ['http://www.example.com/feed.xml']
  8. iterator = 'iternodes' # This is actually unnecessary, since it's the default value
  9. itertag = 'item'
  10.  
  11. def parse_node(self, response, node):
  12. self.logger.info('Hi, this is a <%s> node!: %s', self.itertag, ''.join(node.getall()))
  13.  
  14. item = TestItem()
  15. item['id'] = node.xpath('@id').get()
  16. item['name'] = node.xpath('name').get()
  17. item['description'] = node.xpath('description').get()
  18. return item

Basically what we did up there was to create a spider that downloads a feed fromthe 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[source]
  • This spider is very similar to the XMLFeedSpider, except that it iteratesover rows, instead of nodes. The method that gets called in each iterationis parse_row().

    • delimiter
    • A string with the separator character for each field in the CSV fileDefaults to ',' (comma).

    • quotechar

    • A string with the enclosure character for each field in the CSV fileDefaults to '"' (quotation mark).

    • headers

    • A list of the column names in the CSV file.

    • parserow(_response, row)[source]

    • Receives a response and a dict (representing each row) with a key for eachprovided (or detected) header of the CSV file. This spider also gives theopportunity to override adapt_response and process_results methodsfor pre- and post-processing purposes.

CSVFeedSpider example

Let’s see an example similar to the previous one, but using aCSVFeedSpider:

  1. from scrapy.spiders import CSVFeedSpider
  2. from myproject.items import TestItem
  3.  
  4. class MySpider(CSVFeedSpider):
  5. name = 'example.com'
  6. allowed_domains = ['example.com']
  7. start_urls = ['http://www.example.com/feed.csv']
  8. delimiter = ';'
  9. quotechar = "'"
  10. headers = ['id', 'name', 'description']
  11.  
  12. def parse_row(self, response, row):
  13. self.logger.info('Hi, this is a row!: %r', row)
  14.  
  15. item = TestItem()
  16. item['id'] = row['id']
  17. item['name'] = row['name']
  18. item['description'] = row['description']
  19. return item

SitemapSpider

  • class scrapy.spiders.SitemapSpider[source]
  • SitemapSpider allows you to crawl a site by discovering the URLs usingSitemaps.

It supports nested sitemaps and discovering sitemap urls fromrobots.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 extractsitemap urls from it.

  • sitemap_rules
  • A list of tuples (regex, callback) where:

    • 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 matchthe regular expression. callback can be a string (indicating thename of a spider method) or a callable.For example:
  1. sitemap_rules = [('/product/', 'parse_product')]

Rules are applied in order, and only the first one that matches will beused.

If you omit this attribute, all urls found in sitemaps will beprocessed with the parse callback.

  • sitemap_follow
  • A list of regexes of sitemap that should be followed. This is onlyfor sites that use Sitemap index files that point to other sitemapfiles.

By default, all sitemaps are followed.

  • sitemap_alternate_links
  • Specifies if alternate links for one url should be followed. Theseare links for the same website in another language passed withinthe same url block.

For example:

  1. <url>
  2. <loc>http://example.com/</loc>
  3. <xhtml:link rel="alternate" hreflang="de" href="http://example.com/de"/>
  4. </url>

With sitemap_alternate_links set, this would retrieve both URLs. Withsitemap_alternate_links disabled, only http://example.com/ would beretrieved.

Default is sitemap_alternate_links disabled.

  • sitemapfilter(_entries)[source]
  • This is a filter function that could be overridden to select sitemap entriesbased on their attributes.

For example:

  1. <url>
  2. <loc>http://example.com/</loc>
  3. <lastmod>2005-01-01</lastmod>
  4. </url>

We can define a sitemap_filter function to filter entries by date:

  1. from datetime import datetime
  2. from scrapy.spiders import SitemapSpider
  3.  
  4. class FilteredSitemapSpider(SitemapSpider):
  5. name = 'filtered_sitemap_spider'
  6. allowed_domains = ['example.com']
  7. sitemap_urls = ['http://example.com/sitemap.xml']
  8.  
  9. def sitemap_filter(self, entries):
  10. for entry in entries:
  11. date_time = datetime.strptime(entry['lastmod'], '%Y-%m-%d')
  12. if date_time.year >= 2005:
  13. yield entry

This would retrieve only entries modified on 2005 and the followingyears.

Entries are dict objects extracted from the sitemap document.Usually, the key is the tag name and the value is the text inside it.

It’s important to notice that:

  1. - as the loc attribute is required, entries without this tag are discarded
  2. - alternate links are stored in a list with the key <code>alternate</code>(see <code>sitemap_alternate_links</code>)
  3. - namespaces are removed, so lxml tags named as <code>{namespace}tagname</code> become only <code>tagname</code>

If you omit this method, all entries found in sitemaps will beprocessed, observing other attributes and their settings.

SitemapSpider examples

Simplest example: process all urls discovered through sitemaps using theparse callback:

  1. from scrapy.spiders import SitemapSpider
  2.  
  3. class MySpider(SitemapSpider):
  4. sitemap_urls = ['http://www.example.com/sitemap.xml']
  5.  
  6. def parse(self, response):
  7. pass # ... scrape item here ...

Process some urls with certain callback and other urls with a differentcallback:

  1. from scrapy.spiders import SitemapSpider
  2.  
  3. class MySpider(SitemapSpider):
  4. sitemap_urls = ['http://www.example.com/sitemap.xml']
  5. sitemap_rules = [
  6. ('/product/', 'parse_product'),
  7. ('/category/', 'parse_category'),
  8. ]
  9.  
  10. def parse_product(self, response):
  11. pass # ... scrape product ...
  12.  
  13. def parse_category(self, response):
  14. pass # ... scrape category ...

Follow sitemaps defined in the robots.txt file and only follow sitemapswhose url contains /sitemap_shop:

  1. from scrapy.spiders import SitemapSpider
  2.  
  3. class MySpider(SitemapSpider):
  4. sitemap_urls = ['http://www.example.com/robots.txt']
  5. sitemap_rules = [
  6. ('/shop/', 'parse_shop'),
  7. ]
  8. sitemap_follow = ['/sitemap_shops']
  9.  
  10. def parse_shop(self, response):
  11. pass # ... scrape shop here ...

Combine SitemapSpider with other sources of urls:

  1. from scrapy.spiders import SitemapSpider
  2.  
  3. class MySpider(SitemapSpider):
  4. sitemap_urls = ['http://www.example.com/robots.txt']
  5. sitemap_rules = [
  6. ('/shop/', 'parse_shop'),
  7. ]
  8.  
  9. other_urls = ['http://www.example.com/about']
  10.  
  11. def start_requests(self):
  12. requests = list(super(MySpider, self).start_requests())
  13. requests += [scrapy.Request(x, self.parse_other) for x in self.other_urls]
  14. return requests
  15.  
  16. def parse_shop(self, response):
  17. pass # ... scrape shop here ...
  18.  
  19. def parse_other(self, response):
  20. pass # ... scrape other here ...