Spiders

    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 for the URLs specified in the and the parse method as callback function for the Requests.

    2. In the callback function, you parse the response (web page) and return , 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 ) or written to a file using Feed exports.

    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.

    class scrapy.spiders.Spider

    class scrapy.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 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 instantiated) 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 . 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 (or their subdomains) won’t be followed if OffsiteMiddleware 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 no particular URLs are specified. So, the first pages downloaded will be those listed here. The subsequent Request 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: .

    • crawler

      This attribute is set by the from_crawler() class method after initializating the class, and links to the 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 instance, see the Settings topic for a detailed introduction on this subject.

    • logger

      Python logger created with the Spider’s . You can use it to send log messages through it as described on Logging from Spiders.

    • state

      A dict you can use to persist some spider state between batches. See to know more about it.

    • 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 and settings attributes in the new instance so they can be accessed later inside the spider’s code.

      • Parameters

        • crawler ( instance) – crawler to which the spider will be bound

        • args (list) – arguments passed to the method

        • kwargs (dict) – keyword arguments passed to the method

    • start_requests()

      This method must return an iterable with the first Requests to crawl for this spider. It is called by Scrapy when the spider is opened for scraping. Scrapy calls it only once, so it is safe to implement start_requests() as a generator.

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

      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:

    • 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 item objects.

      • Parameters

        response () – the response to parse

    • log(message[, level, component])

      Wrapper that sends a log message through the Spider’s logger, kept for backward compatibility. For more information see .

    • closed(reason)

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

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

    Return multiple Requests and items from a single callback:

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

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

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

    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 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. class MySpider(scrapy.Spider):
    3. name = 'myspider'
    4. def __init__(self, category=None, *args, **kwargs):
    5. super(MySpider, self).__init__(*args, **kwargs)
    6. self.start_urls = [f'http://www.example.com/categories/{category}']
    7. # ...

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

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

    If you are running Scrapy from a script, you can specify spider arguments when calling or CrawlerRunner.crawl:

    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 list using something like or json.loads() and 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 credentials used by or the user agent used 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 .

    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:

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

    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:

    • rules

      Which is a list of one (or more) Rule objects. Each 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 overridable method:

    • parse_start_url(response, \*kwargs*)[source]

      This method is called for each response produced for the URLs in the spider’s start_urls attribute. It allows to parse the initial responses and must return either an , a object, 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)

    link_extractor is a Link Extractor object which defines how links will be extracted from each crawled page. Each produced link will be used to generate a Request object, which will contain the link’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 spider object with that name will be used) to be called for each link extracted with the specified link extractor. This callback receives a as its first argument and must return either a single instance or an iterable of item objects and/or Request objects (or any subclass of them). As mentioned above, the received object will contain the text of the link that produced the Request in its meta dictionary (under the link_text key)

    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 for every Request extracted by this rule. This callable should take said request as first argument and the Response from which the request originated as second argument. It must return a Request object or None (to filter out the request).

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

    Warning

    Because of its internal implementation, you must explicitly set callbacks for new requests when writing CrawlSpider-based spiders; unexpected behaviour can occur otherwise.

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

    class scrapy.spiders.XMLFeedSpider[source]

    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:

      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 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 attribute.

      Example:

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

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

    • adapt_response(response)[source]

      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)

    • process_results(response, results)[source]

      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).

    Warning

    Because of its internal implementation, you must explicitly set callbacks for new requests when writing -based spiders; unexpected behaviour can occur otherwise.

    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. class MySpider(XMLFeedSpider):
    4. name = 'example.com'
    5. allowed_domains = ['example.com']
    6. start_urls = ['http://www.example.com/feed.xml']
    7. iterator = 'iternodes' # This is actually unnecessary, since it's the default value
    8. itertag = 'item'
    9. self.logger.info('Hi, this is a <%s> node!: %s', self.itertag, ''.join(node.getall()))
    10. item['id'] = node.xpath('@id').get()
    11. item['name'] = node.xpath('name').get()
    12. item['description'] = node.xpath('description').get()
    13. 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.

    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 column names in the CSV file.

    • 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 :

    class scrapy.spiders.SitemapSpider[source]

    SitemapSpider allows you to crawl a site by discovering the URLs using .

    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 and it will be parsed to extract sitemap 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 match the regular expression. callback can be a string (indicating the name 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 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 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:

      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. With sitemap_alternate_links disabled, only http://example.com/ would be retrieved.

      Default is sitemap_alternate_links disabled.

    • sitemap_filter(entries)

      This is a filter function that could be overridden to select sitemap entries based 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. class FilteredSitemapSpider(SitemapSpider):
      4. name = 'filtered_sitemap_spider'
      5. allowed_domains = ['example.com']
      6. sitemap_urls = ['http://example.com/sitemap.xml']
      7. def sitemap_filter(self, entries):
      8. for entry in entries:
      9. date_time = datetime.strptime(entry['lastmod'], '%Y-%m-%d')
      10. if date_time.year >= 2005:
      11. yield entry

      This would retrieve only entries modified on 2005 and the following years.

      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:

      • as the loc attribute is required, entries without this tag are discarded

      • alternate links are stored in a list with the key alternate (see sitemap_alternate_links)

      • namespaces are removed, so lxml tags named as {namespace}tagname become only tagname

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

    SitemapSpider examples

    Simplest example: process all urls discovered through sitemaps using the parse callback:

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

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

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

    Follow sitemaps defined in the file and only follow sitemaps whose url contains /sitemap_shop:

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