Crawling and Following Links
9 min read
Welcome, intrepid data adventurer! πΊοΈ So, you've learned to snatch data from a single page. But what if the information you seek is scattered across multiple pages, like a trail of digital breadcrumbs? Fear not! This guide will equip you with the skills to navigate the web's interconnected highways and byways using Scrapy.
1. Extracting Links from Pages π
The Problem: You've landed on a page, and it's full of tantalizing links to other pages you need to visit. How do you grab them?
The Solution: Scrapy provides powerful selectors to extract data, and that includes the href attributes of anchor (<a>) tags, which hold the URLs.
Imagine you're at a grand library (the website). You're in the main hall (the starting page), and you see signs pointing to different sections (links). To get to the "History" section, you need to follow the sign that says "History."
In Scrapy, you can use CSS or XPath selectors to find these "signs."
Example Time! π
Let's say you're on a fictional bookstore's homepage, and you want to get the links to all the book categories. The HTML might look something like this:
<div class="categories">
<a href="/category/fiction">Fiction</a>
<a href="/category/non-fiction">Non-Fiction</a>
<a href="/category/science">Science</a>
</div>You can extract these links in your spider's parse method like this:
import scrapy
class BookSpider(scrapy.Spider):
name = 'bookspider'
start_urls = ['http://books.toscrape.com']
def parse(self, response):
# Using CSS selectors
category_links = response.css('div.categories a::attr(href)').getall()
for link in category_links:
# If the link is relative, you need to join it with the base URL
yield response.follow(link, callback=self.parse_category)Under the Hood: π΅οΈββοΈ
response.css('div.categories a::attr(href)'): This is a CSS selector that says, "Find all<a>tags that are inside a<div>with the classcategories, and from those<a>tags, get me the value of thehrefattribute."getall(): This method returns a list of all the extracted links.response.follow(): This is a handy shortcut in Scrapy to create a newscrapy.Requestfor the given URL. It automatically handles relative URLs by joining them with the response's URL.
A Funny Exaggeration: Trying to manually copy and paste every link from a website is like trying to empty the ocean with a teaspoon. It's a noble effort, but you'll be there for a while. Let Scrapy be your giant, automated bucket!
2. Yielding scrapy.Request to Follow Pagination πβ‘οΈπ
The Problem: You're scraping a list of products, but they are spread across multiple pages (e.g., page 1, page 2, page 3...). How do you tell your spider to go to the next page?
The Solution: You find the "Next" button's link and yield a new scrapy.Request to that URL, telling Scrapy to crawl it.
Think of it like reading a book. When you finish a page, you instinctively turn to the next one. For a Scrapy spider, the "Next" button is the signal to turn the page.
Example Time! π
Most websites with pagination have a "Next" button with a link to the next page. Let's say the HTML for the "Next" button looks like this:
<li class="next">
<a href="/catalogue/page-2.html">next</a>
</li>You can follow this link in your spider:
import scrapy
class ProductSpider(scrapy.Spider):
name = 'productspider'
start_urls = ['http://books.toscrape.com/catalogue/category/books/travel_2/index.html']
def parse(self, response):
# ... your code to scrape data from the current page ...
# Find the "Next" button's link
next_page = response.css('li.next a::attr(href)').get()
if next_page is not None:
# If there is a next page, create a new request to it
yield response.follow(next_page, callback=self.parse)Under the Hood: π΅οΈββοΈ
response.css('li.next a::attr(href)').get(): This selector targets thehrefattribute of the<a>tag inside the<li>with the class "next".get()retrieves the first match.if next_page is not None:: This is a crucial check. On the last page, there won't be a "Next" button, so this prevents your spider from trying to follow a non-existent link.yield response.follow(next_page, callback=self.parse): We're telling Scrapy to follow thenext_pagelink and then call the sameparsemethod to process the new page. This creates a loop that continues until there are no more "Next" buttons to click. This is a very common and powerful pattern for handling pagination.
3. Passing Data Between Callbacks Using cb_kwargs π
The Problem: You scrape some data from a list page (like a product name) and then follow a link to a detail page to get more information (like the product description). How do you keep the product name when you get to the detail page?
The Solution: You can pass data from one callback function to another using the cb_kwargs (callback keyword arguments) parameter in your scrapy.Request.
Imagine you're on a treasure hunt. You find a clue on one island (the list page) that tells you where the next clue is. You need to carry that first clue with you to the next island (the detail page) to make sense of the new information. cb_kwargs is like a magical backpack for your data.
Example Time! π
Let's say on the book list page, you get the title and the link to the book's detail page.
import scrapy
class BookDetailSpider(scrapy.Spider):
name = 'bookdetailspider'
start_urls = ['http://books.toscrape.com/']
def parse(self, response):
for book in response.css('article.product_pod'):
book_title = book.css('h3 a::attr(title)').get()
detail_page_link = book.css('h3 a::attr(href)').get()
yield response.follow(detail_page_link,
callback=self.parse_book_details,
cb_kwargs={'title': book_title})
def parse_book_details(self, response, title):
description = response.css('div#product_description + p::text').get()
yield {
'title': title,
'description': description
}Under the Hood: π΅οΈββοΈ
cb_kwargs={'title': book_title}: When creating the request to the detail page, we pass a dictionary tocb_kwargs. Here, we're passing thebook_titlewe just scraped.def parse_book_details(self, response, title):: In the callback functionparse_book_details, we can now accepttitleas an argument. Scrapy automatically unpacks thecb_kwargsdictionary and passes its items as keyword arguments to the callback.
Industry Practice: While you might see older Scrapy code using meta to pass data, cb_kwargs is the modern and preferred way for passing user-defined data between callbacks as it's more explicit and less prone to conflicts with Scrapy's internal mechanisms.
4. Introduction to CrawlSpider and Rules π€π
The Problem: Your crawling logic is getting complex. You're following links to categories, then to sub-categories, then to product pages, and also handling pagination. Your parse method is turning into a tangled mess of if statements.
The Solution: CrawlSpider allows you to define a set of Rules that declaratively state how to follow links and which callback functions to use for different types of pages.
Think of a regular spider as a new driver who has to manually decide at every intersection whether to turn left, right, or go straight. A CrawlSpider is like a self-driving car with a pre-programmed route. You just tell it the rules of the road (e.g., "on roads named 'category', turn here and look for 'products'"), and it handles the navigation.
Example Time! π
Let's create a CrawlSpider to crawl a bookstore, following category links and then scraping data from the book detail pages.
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
class BookCrawlSpider(CrawlSpider):
name = 'bookcrawlspider'
allowed_domains = ['books.toscrape.com']
start_urls = ['http://books.toscrape.com/']
rules = (
Rule(LinkExtractor(restrict_css='article.product_pod h3 a'), callback='parse_item'),
Rule(LinkExtractor(restrict_css='li.next a')),
)
def parse_item(self, response):
yield {
'title': response.css('div.product_main h1::text').get(),
'price': response.css('p.price_color::text').get(),
}Under the Hood: π΅οΈββοΈ
from scrapy.spiders import CrawlSpider, Rule: We import the necessary classes.from scrapy.linkextractors import LinkExtractor: We also importLinkExtractor, which is a helper class to extract links.rules = (: We define a tuple ofRuleobjects.Rule(LinkExtractor(restrict_css='article.product_pod h3 a'), callback='parse_item'): This is our first rule.LinkExtractor(restrict_css='article.product_pod h3 a'): This will extract links that match the CSS selector for book detail pages.callback='parse_item': When a link is followed, the response will be passed to theparse_itemmethod.
Rule(LinkExtractor(restrict_css='li.next a')): This is our second rule for pagination.- Notice there's no
callback. By default,followisTrueif no callback is specified, meaning the spider will extract links from these pages and continue applying the rules.
- Notice there's no
Interesting Fact: The CrawlSpider was one of the original features of Scrapy, designed to make it easier to scrape entire websites by just defining the structure of the site.
5. Configuring LinkExtractor for Automated Navigation βοΈπ§
The Problem: You want more control over which links CrawlSpider follows. Maybe you only want to follow links that contain a certain keyword or exclude links to certain file types.
The Solution: The LinkExtractor class has several useful parameters to fine-tune its behavior.
This is like giving your self-driving car more specific instructions. Instead of just "follow the main road," you can say "follow the main road, but avoid any roads that lead to a dead end, and only take roads that have 'scenic view' in their name."
Commonly Used LinkExtractor Parameters:
allow: A regular expression (or a list of them) that the absolute URL must match to be extracted.deny: A regular expression (or a list of them) to exclude URLs.restrict_xpaths: Extracts links only from the regions of the page specified by an XPath.restrict_css: Extracts links only from the regions specified by a CSS selector.allow_domains: A domain or list of domains to consider for link extraction.
Example Time! π
Let's refine our CrawlSpider to only follow links to books in the "Travel" category. The URL for the travel category is http://books.toscrape.com/catalogue/category/books/travel_2/index.html.
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
class TravelBookCrawlSpider(CrawlSpider):
name = 'travelbookcrawlspider'
allowed_domains = ['books.toscrape.com']
start_urls = ['http://books.toscrape.com/catalogue/category/books/travel_2/index.html']
rules = (
Rule(LinkExtractor(allow=r'catalogue/'), callback='parse_item', follow=True),
)
def parse_item(self, response):
if response.css('div.product_main h1::text').get():
yield {
'title': response.css('div.product_main h1::text').get(),
'price': response.css('p.price_color::text').get(),
}Under the Hood: π΅οΈββοΈ
Rule(LinkExtractor(allow=r'catalogue/'), callback='parse_item', follow=True):allow=r'catalogue/': This regular expression will ensure that we only extract links that have "catalogue/" in their URL. This is a simple way to stay within the product section of the site.callback='parse_item': When a link is followed, callparse_item.follow=True: This tells the spider to continue extracting links from the pages it follows.
A Parting Thought: Crawling and following links is where the "spider" in web scraping truly comes to life. You're not just grabbing what's on one page; you're exploring the vast, interconnected web of information. Happy crawling! πΈοΈ
References
Challenge
You are tasked with building a Scrapy spider to scrape data from http://quotes.toscrape.com. Your spider must handle pagination to visit all pages of quotes and follow links to individual author pages to gather complete information.
Requirements:
- Spider Name: Name your spider
quote_crawler. - Starting Point: The spider should begin crawling from
http://quotes.toscrape.com. - Main Parsing Logic (
parsemethod):- For each quote on a page, you must extract:
- The quote text.
- A list of tags associated with the quote.
- The URL to the author's detail page.
- After extracting the above,
yielda new request to the author's detail page usingresponse.follow(). - This new request must use
self.parse_authoras its callback function. - Crucially, you must pass the extracted quote text and tags to the
parse_authorcallback using thecb_kwargsargument. - After processing all quotes on the current page, find the link to the "Next" page.
- If a "Next" page link exists,
yielda new request to follow it, using the sameparsemethod as the callback to continue the process.
- For each quote on a page, you must extract:
- Author Parsing Logic (
parse_authormethod):- This method will receive the
responsefrom the author's page, as well as thetextandtagspassed viacb_kwargs. - From the author's detail page, extract:
- The author's full name.
- The author's birthdate.
- The author's birth location.
- Finally,
yielda single dictionary with the keystext,author,born, andtags. The value for thebornkey should be a string combining the birthdate and location (e.g., "Month Day, Year in Location").
- This method will receive the
Expected result
Your completed Scrapy spider should be capable of navigating the entire quotes.toscrape.com website. It must start on the first page, follow the "Next" button through all subsequent pages, and for every quote it finds, it must follow the link to the author's detail page.
The final output of the spider will be a stream of yielded Python dictionaries, one for each quote. Each dictionary must have the following structure and keys:
text: The full text of the quote (string).author: The full name of the author (string).born: A single string combining the author's birth date and location (string).tags: A list of strings, where each string is a tag associated with the quote.
Example of a single yielded dictionary:
{
"text": "The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.",
"author": "Albert Einstein",
"born": "March 14, 1879 in Ulm, Germany",
"tags": ["change", "deep-thoughts", "thinking", "world"]
}