Learn Scrapy · 2/13

Your First Scrapy Spider

7 min read

🕷️ Your First Scrapy Spider: Let's Get Crawling!

Welcome, aspiring data wrangler! So far, we've set up our Scrapy project. Now, it's time to build the heart of our operation: the Spider.

A Spider is a class that you define, and Scrapy uses it to scrape information from a website (or a group of websites). Think of it as a blueprint for a smart, autonomous robot you're about to unleash on the web to fetch data for you. But before we can let it run wild, we need to give it some instructions!


1. Generating a Spider: The genspider Command

The Problem: Manually creating a spider file, writing the boilerplate code (the basic structure that's always the same), and making sure it's in the right directory is tedious. It's easy to make a typo and spend the next hour debugging a simple mistake.

The Solution: Scrapy provides a handy command-line tool, genspider, to generate a new spider for us with a pre-filled template. It's like having a robot that builds other robots. Automation is a beautiful thing, isn't it?

To get started, navigate to your Scrapy project's root directory in your terminal. This is the directory that contains the scrapy.cfg file.

Now, run the following command:

bash
scrapy genspider <spider_name> <domain_to_crawl>

Let's break that down:

  • scrapy genspider: This is the command to generate a new spider.
  • <spider_name>: This is the unique name you'll use to identify and run your spider. Keep it short, descriptive, and without spaces (e.g., quote_spider, book_finder).
  • <domain_to_crawl>: This is the website domain you want to scrape (e.g., quotes.toscrape.com, books.toscrape.com).

Example in Action 🎬

Let's create a spider to crawl quotes.toscrape.com, a website made for practicing web scraping.

bash
scrapy genspider quotes quotes.toscrape.com

After running this, Scrapy will work its magic and create a new file for you. ✨

ceylon
Created spider 'quotes' in module 'myproject.spiders.quotes'

You will now find a new file at myproject/spiders/quotes.py. This isn't just an empty file; it's a fully functional, albeit basic, spider ready for your instructions!


2. Anatomy of a Basic Spider (name, allowed_domains, start_urls)

Let's open up that shiny new quotes.py file. It's time for a dissection! 🔬 You'll see something like this:

python
import scrapy

class QuotesSpider(scrapy.Spider):
    name = "quotes"
    allowed_domains = ["quotes.toscrape.com"]
    start_urls = ["https://quotes.toscrape.com/"]

    def parse(self, response):
        pass

This might look simple, but these few lines are the complete brain and nervous system of your spider. Let's look at the three main attributes:

  • name: This is the unique identifier for your spider. It's how you'll tell Scrapy which spider to run. The name must be unique within a project.

    • Why it's important: If you have multiple spiders in a project (e.g., one for quotes, one for authors), this is how you differentiate them.
  • allowed_domains: This is a list of domains that your spider is allowed to crawl.

    • Think of it this way: allowed_domains acts like a bouncer at an exclusive club. If your spider finds a link to another website (say, google.com), this bouncer will check its list. If google.com isn't on the list, the spider is not allowed to follow that link. This is a crucial safety feature to prevent your spider from accidentally wandering off and trying to download the entire internet. You wouldn't want a massive cloud bill because your little spider decided to explore Wikipedia, would you? 😂
  • start_urls: This is a list of URLs where your spider will begin its journey.

    • The starting line: When you run your spider, it will make a request to each URL in this list. The responses it gets back are the first pages it will process. For our example, it starts at the homepage of the quotes website.

3. Writing the parse Method: Handling the Response

The Problem: Our spider can now visit a webpage. Great! But... what does it do when it gets there? Right now, its parse method just has a pass statement, which is Python's way of saying "do absolutely nothing." We need to teach it how to read the page and find the data we want.

The Solution: The parse method is the workhorse of our spider. Scrapy calls this method for each URL in start_urls. The response object it receives as an argument is a treasure trove—it contains the entire HTML content of the page, plus other useful metadata.

Our job inside parse is to extract the data. The most common way to do this is by using CSS Selectors. If you've ever used CSS to style a webpage, you're already halfway there!

Let's update our parse method to extract all the quotes from the page.

python
# Inside myproject/spiders/quotes.py

import scrapy

class QuotesSpider(scrapy.Spider):
    name = "quotes"
    allowed_domains = ["quotes.toscrape.com"]
    start_urls = ["https://quotes.toscrape.com/"]

    def parse(self, response):
        # We use a CSS selector to find all the 'div' elements with the class 'quote'
        quotes = response.css('div.quote')

        # Now, we loop through each quote element we found
        for quote in quotes:
            # Inside each 'div.quote', we find the text and the author
            text = quote.css('span.text::text').get()
            author = quote.css('small.author::text').get()

            # We 'yield' a Python dictionary containing the data
            yield {
                'text': text,
                'author': author,
            }

Let's break down that parse method:

  1. response.css('div.quote'): This line uses a CSS selector to grab every <div> element that has a class of quote. It returns a list-like object containing all the matches.
  2. for quote in quotes:: We loop through each of the quote blocks we found.
  3. quote.css('span.text::text').get(): Within each quote block, we now look for a <span> with the class text. The ::text part is a CSS pseudo-selector that tells Scrapy we want to extract the text content from inside that tag. .get() fetches the first result.
  4. yield { ... }: This is a special Python keyword. Instead of returning data, which would stop the function, yield sends the dictionary back to the Scrapy engine and continues the loop. This is how Scrapy efficiently collects all the data you find.

Fun Fact: The yield keyword makes the function a "generator." Generators are memory-efficient because they produce items one at a time, rather than creating a massive list of all the results in memory. For scraping thousands of pages, this is a lifesaver!


4. Running the Spider and Exporting Data to JSON/CSV

The Problem: We've taught our spider how to find the data. Now we need to actually run it and, most importantly, save the collected data in a useful format. Printing it to the console is cool for debugging, but we need a real file.

The Solution: Scrapy makes this incredibly simple with the crawl command and built-in "Feed Exports."

To run your spider, go back to your terminal (in the project's root directory) and run:

bash
scrapy crawl quotes

You'll see a lot of text fly by in your terminal. This is Scrapy's log, showing you what's happening under the hood—it's making requests, getting responses, and our spider is busy parsing!

But where did the data go? It was just logged to the console. To save it to a file, we can use the -o (for output) flag.

Exporting to JSON 💾

JSON (JavaScript Object Notation) is a very popular, human-readable format for data. To save your scraped items as a JSON file, run this:

bash
scrapy crawl quotes -o quotes.json

Scrapy will automatically create a quotes.json file in your project directory filled with all the quotes and authors it found. No extra code needed!

Exporting to CSV 📊

Need your data in a spreadsheet-friendly format like CSV (Comma-Separated Values)? Easy. Just change the file extension:

bash
scrapy crawl quotes -o quotes.csv

And voilà! You now have a quotes.csv file ready to be opened in Excel, Google Sheets, or any data analysis tool.

You've officially built and run your first Scrapy spider from start to finish. You told it where to go, what to look for, and how to save its findings. Congratulations! 🎉 You're now ready to tackle more complex websites and data extraction challenges.


📚 Extra Reading & References

Challenge

You are tasked with building a Scrapy spider to extract product details from a fictional e-commerce site. Write a complete Scrapy spider class named ProductSpider.

Requirements:

  1. The spider's name attribute must be 'product_scraper'.
  2. The allowed_domains attribute should be a list containing only 'myfakestore.com'.
  3. The start_urls attribute should be a list containing the URL 'http://myfakestore.com/products/item123'.
  4. Implement the parse method to extract the following information from the response.

Target HTML Structure:

  • The product name is inside an <h1> tag with the class product-title.
  • The price is inside a <span> tag with the id product-price.
  • The stock status (e.g., "In Stock") is inside a <p> tag with the class stock-status.
  • Each customer review is contained within a <div> with the class review.
    • Inside each review div, the author's name is in a <strong> tag with the class review-author.
    • The review text is in a <p> tag with the class review-text.

parse Method Logic:

  • Your parse method should extract the product name, price, and stock status.
  • It must then find all review divs and loop through them.
  • Inside the loop, extract the author and text for each review.
  • Finally, yield a single Python dictionary. This dictionary should contain the product's name, price, stock status, and a key named 'reviews' which holds a list of all the extracted reviews. Each review in the list should be a dictionary with 'author' and 'comment' keys.

Expected result

Your code should be a single Python class ProductSpider that inherits from scrapy.Spider. It must define the name, allowed_domains, and start_urls class attributes correctly. The parse method should use response.css() selectors to extract the product name, price, stock status, and then iterate through all reviews to extract author and comment data, yielding a single dictionary with a nested list for the reviews.

python
import scrapy

class ProductSpider(scrapy.Spider):
    name = 'product_scraper'
    allowed_domains = ['myfakestore.com']
    start_urls = ['http://myfakestore.com/products/item123']

    def parse(self, response):
        reviews_list = []
        reviews = response.css('div.review')

        for review in reviews:
            author = review.css('strong.review-author::text').get()
            comment = review.css('p.review-text::text').get()
            reviews_list.append({
                'author': author,
                'comment': comment
            })

        yield {
            'name': response.css('h1.product-title::text').get(),
            'price': response.css('span#product-price::text').get(),
            'stock_status': response.css('p.stock-status::text').get(),
            'reviews': reviews_list
        }
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.