Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • webscraping
  • Beautiful Soup
  • Selenium
  • Scrapy
  • urllib
  • open cv
  • Data analysis
  • Machine learning
  • NLP
  • Deep learning
  • Data Science
  • Interview question
  • ML math
  • ML Projects
  • ML interview
  • DL interview
Open In App
Next Article:
Collecting data with Scrapy
Next article icon

Scrapy - Exceptions

Last Updated : 24 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Python-based Scrapy is a robust and adaptable web scraping platform. It provides a variety of tools for systematic, effective data extraction from websites. It helps us to automate data extraction from numerous websites.

Scrapy Python

Scrapy describes the spider that browses websites and gathers data in a clear and concise manner. The spider is in charge of accessing the websites, extracting the information, and storing it in a database or a local file. Additionally, complicated websites that employ JavaScript to load data or require authentication can be handled by Scrapy.

In fields like e-commerce, data science, and market research where data extraction from numerous websites is frequently needed, Scrapy is used extensively. It also serves as a framework for teaching web scraping in Python because it is simple to understand.

Exceptions in Scrapy

Errors or extraordinary occurrences that can happen when web scraping are known as exceptions in Scrapy. Invalid data, coding flaws, and network failures are just a few of the causes of these. An exception in Python is a sign that there has been a problem or an unexpected condition that needs to be handled.

Required Module

pip install scrapy

In Scrapy, a few typical instances that can happen are as follows:

Scrapy - Exceptions
 

DropItem

If you want to remove an item from the pipeline, this exception is triggered. It signals that a certain item should be dropped and not processed any further by the Item Pipeline. To use DropItem, raise the exception and provide an optional reason for dropping the item.

Here, data is missing in the item, hence Dropitem exception will be raised and the item will be dropped for further processing.

Python3
import scrapy from scrapy.exceptions import DropItem   class MySpider(scrapy.Spider):     name = "GeeksforGeeks||chsaagar27"      def parse(self, response):         item = MyItem()         if not item.get('data'):             raise DropItem("Missing data in %s" % item)         return item 

CloseSpider

When you wish to stop the spider from running, you can raise the CloseSpider exception. You may utilize this exception when you have completed your objective or need to halt the spider for any other reason.

Whenever we get our requirements done then we can signal to stop the spider for further processing.

In the example, if the some_condition is met during the spider's execution, the CloseSpider exception will be raised with the reason "finished", causing the spider to stop immediately.

Python3
import scrapy from scrapy.exceptions import CloseSpider  class MySpider(scrapy.Spider):     name = "GeeksforGeeks||chsaagar27"      def parse(self, response):         if some_condition:             raise CloseSpider("Finished") 

In the example, if the some_condition is met during the pipeline processing, the CloseSpider exception will be raised with the reason "Goal reached", causing the spider to stop immediately.

Python3
import scrapy from scrapy.exceptions import CloseSpider  class MyPipeline:     def process_item(self, item, spider):         if some_condition:             raise CloseSpider("Finished")         else:             return item 

IgnoreRequest

This exception is thrown when a spider-generated request is to be disregarded. When you come across an invalid URL or want to exclude particular queries, this can be helpful. It is used when we want to filter out certain requests before they are sent, for example, if the request is a duplicate or if the URL is invalid.

In the example, if the is_valid_url function returns False for a URL, the IgnoreRequest exception will be raised and the corresponding request will not be processed any further.

Python3
import scrapy from scrapy.exceptions import IgnoreRequest  class MySpider(scrapy.Spider):     name = "GeeksforGeeks||chsaagar27"      def start_requests(self):         for url in urls:             if not is_valid_url(url):                 raise IgnoreRequest("Invalid URL: %s" % url)             yield scrapy.Request(url=url, callback=self.parse) 

In the example, if the some_condition is met during the middleware processing, the IgnoreRequest exception will be raised and the corresponding request will not be processed any further.

Python3
import scrapy from scrapy.exceptions import IgnoreRequest  class MyMiddleware:     def process_request(self, request, spider):         if some_condition:             raise IgnoreRequest("Request ignored: %s" % request.url)         else:             return None 

NotConfigured

When a crucial configuration setting is either absent or ineffective, the NotConfigured exception is thrown. It is used to indicate that the extension or middleware is not properly configured and cannot be used.

In the example, the from_crawler method checks if two required settings (SETTING_1 and SETTING_2) are present in the Scrapy settings. If one or both of the settings are missing, the NotConfigured exception is raised with an appropriate error message.

Python3
import scrapy from scrapy.exceptions import NotConfigured  class MyExtension:      def from_crawler(cls, crawler):         setting1 = crawler.settings.get('SETTING_1')         setting2 = crawler.settings.get('SETTING_2')          if not setting1 or not setting2:             raise NotConfigured("SETTING_1 and \                         SETTING_2 must be set")          return cls(setting1, setting2) 

NotSupported

This exception is thrown when Scrapy does not support a particular feature or functionality. It is used to indicate that a certain feature or functionality is not supported or implemented. This exception can be useful in situations where you want to indicate to the user or developer that a particular operation or configuration is not allowed or not currently available.

In the example above, if the some_condition is met during the spider's execution, the NotSupported exception will be raised with an appropriate error message.

Python3
import scrapy from scrapy.exceptions import NotSupported   class MySpider(scrapy.Spider):     name = "GeeksforGeeks||chsaagar27"      def parse(self, response):         if some_condition:             raise NotSupported("operation-->not supported") 

UsageError

When a command line parameter or option is illegal or absent, this exception is thrown. This exception can be useful in situations where you want to provide feedback to the user or developer about how to correctly use the command or script.

In the example, if the input_file argument is not provided when running the script, the UsageError exception will be raised with an appropriate error message.

Python3
import scrapy from scrapy.exceptions import UsageError   def my_script(args):      if not args.input_file:         raise UsageError("Input file is required") 

DeprecationWarning

Use of a deprecated feature or functionality in Scrapy results in the exception ScrapyDeprecationWarning.This warning can be useful in situations where you want to inform the user or developer that they should update their code to use a newer or different approach.

In the example, if my_function() is called, a ScrapyDeprecationWarning warning will be raised with an appropriate message.

Python3
import scrapy import warnings from scrapy.exceptions import ScrapyDeprecationWarning  def my_function():     warnings.warn(         "my_function() is deprecated, \                 use my_new_function() instead",         ScrapyDeprecationWarning) 

DontCloseSpider 

"DontCloseSpider" is used as that exception which restricts the scrapy to close the spider when it came to the end of the processing of different items and prevents scrapy from being shut down, "DontCloseSpider" is frequently used.

In the example, close_spider() is a function that prevents Scrapy not to close the spider until it is explicitly stopped or encounters an error.

Python3
from scrapy.exceptions import DontCloseSpider from scrapy.spiders import Spider  class MySpider(Spider):     name = 'Geeks for Geeks || chsaagar27'      def parse(self, response):         # process      def close_spider(self, spider):         raise DontCloseSpider 

StopDownload

"StopDownload" is recently added in version 2.2 and it is raised in the downloader middleware to restrict the processing of a request and also prevent it from being downloaded. It is best suited for situations when there is a need to filter out specific requests based on particular rules & without actually downloading them.

In the example, requestprocess() is a function that checks for a specific condition is met or not, and if the condition is met(True) then it raises the "StopDownload" exception which stops the processing of the request and prevents it from being downloaded but if the condition is false then the function returns None and let the request to be processed further.

Python3
from scrapy.exceptions import StopDownload   class Middleware:     def requestprocess(self, request, spider):         if some_condition:             raise StopDownload("Request stopped")         else:             return None 

Next Article
Collecting data with Scrapy
author
chsaagar27
Improve
Article Tags :
  • Python
  • Python-Scrapy
Practice Tags :
  • python

Similar Reads

  • Implementing Web Scraping in Python with Scrapy
    Nowadays data is everything and if someone wants to get data from webpages then one way to use an API or implement Web Scraping techniques. In Python, Web scraping can be done easily by using scraping tools like BeautifulSoup. But what if the user is concerned about performance of scraper or need to
    5 min read
  • Getting Started With Scrapy

    • Scraping dynamic content using Python-Scrapy
      Let's suppose we are reading some content from a source like websites, and we want to save that data on our device. We can copy the data in a notebook or notepad for reuse in future jobs. This way, we used scraping(if we didn't have a font or database, the form brute removes the data in documents, s
      4 min read

    • How to Install Python Scrapy on Windows?
      Scrapy is a web scraping library that is used to scrape, parse and collect web data. Now once our spider has scrapped the data then it decides whether to: Keep the data.Drop the data or items.stop and store the processed data items. In this article, we will look into the process of installing the Sc
      2 min read

    • How to Install Scrapy on MacOS?
      In this article, we will learn how to install Scrapy in Python on MacOS. Scrapy is a fast high-level web crawling and web scraping framework used to crawl websites and extract structured data from their pages. It can be used for a wide range of purposes, from data mining to monitoring and automated
      2 min read

    Scrapy Basics

    • Scrapy - Command Line Tools
      Prerequisite: Implementing Web Scraping in Python with Scrapy Scrapy is a python library that is used for web scraping and searching the contents throughout the web. It uses Spiders which crawls throughout the page to find out the content specified in the selectors. Hence, it is a very handy tool to
      5 min read

    • Scrapy - Item Loaders
      In this article, we are going to discuss Item Loaders in Scrapy. Scrapy is used for extracting data, using spiders, that crawl through the website. The obtained data can also be processed, in the form, of Scrapy Items. The Item Loaders play a significant role, in parsing the data, before populating
      15+ min read

    • Scrapy - Item Pipeline
      Scrapy is a web scraping library that is used to scrape, parse and collect web data. For all these functions we are having a pipelines.py file which is used to handle scraped data through various components (known as class) which are executed sequentially. In this article, we will be learning throug
      10 min read

    • Scrapy - Selectors
      Scrapy Selectors as the name suggest are used to select some things. If we talk of CSS, then there are also selectors present that are used to select and apply CSS effects to HTML tags and text. In Scrapy we are using selectors to mention the part of the website which is to be scraped by our spiders
      7 min read

    • Scrapy - Shell
      Scrapy is a well-organized framework, used for large-scale web scraping. Using selectors, like XPath or CSS expressions, one can scrape data seamlessly. It allows systematic crawling, and scraping the data, and storing the content in different file formats. Scrapy comes equipped with a shell, that h
      9 min read

    • Scrapy - Spiders
      Scrapy is a free and open-source web-crawling framework which is written purely in python. Thus, scrapy can be installed and imported like any other python package. The name of the package is self-explanatory. It is derived from the word 'scraping' which literally means extracting desired substance
      11 min read

    • Scrapy - Feed exports
      Scrapy is a fast high-level web crawling and scraping framework written in Python used to crawl websites and extract structured data from their pages. It can be used for many purposes, from data mining to monitoring and automated testing. This article is divided into 2 sections:Creating a Simple web
      5 min read

    • Scrapy - Link Extractors
      In this article, we are going to learn about Link Extractors in scrapy. "LinkExtractor" is a class provided by scrapy to extract links from the response we get while fetching a website. They are very easy to use which we'll see in the below post.  Scrapy - Link Extractors Basically using the "LinkEx
      5 min read

    • Scrapy - Settings
      Scrapy is an open-source tool built with Python Framework. It presents us with a strong and robust web crawling framework that can easily extract the info from the online page with the assistance of selectors supported by XPath. We can define the behavior of Scrapy components with the help of Scrapy
      7 min read

    • Scrapy - Sending an E-mail
      Prerequisites: Scrapy Scrapy provides its own facility for sending e-mails which is extremely easy to use, and it’s implemented using Twisted non-blocking IO, to avoid interfering with the non-blocking IO of the crawler. This article discusses how mail can be sent using scrapy.  For this MailSender
      2 min read

    • Scrapy - Exceptions
      Python-based Scrapy is a robust and adaptable web scraping platform. It provides a variety of tools for systematic, effective data extraction from websites. It helps us to automate data extraction from numerous websites. Scrapy Python Scrapy describes the spider that browses websites and gathers dat
      7 min read

    Data Collection and Management

    • Collecting data with Scrapy
      Prerequisites:  Scrapy SQLite3 Scrapy is a web scraping library that is used to scrape, parse and collect web data. Now once our spider has scrapped the data then it decides whether to: Keep the data.Drop the data or items.stop and store the processed data items. Hence for all these functions, we ar
      10 min read

    • How to move all files from one directory to another using Python ?
      In this article, we will see how to move all files from one directory to another directory using Python.  In our day-to-day computer usage we generally copy or move files from one folder to other, now let's see how to move a file in Python: This can be done in two ways:Using os module.Using shutil m
      2 min read

    Data Extraction and Export

    • How to Convert Scrapy item to JSON?
      Prerequisite:  scrapyJSON Scrapy is a web scraping tool used to collect web data and can also be used to modify and store data in whatever form we want. Whenever data is being scraped by the spider of scrapy, we are converting that raw data to items of scrapy, and then we will pass that item for fur
      8 min read

    • Saving scraped items to JSON and CSV file using Scrapy
      In this article, we will see how to use crawling with Scrapy, and, Exporting data to JSON and CSV format. We will scrape data from a webpage, using a Scrapy spider, and export the same to two different file formats. Here we will extract from the link  http://quotes.toscrape.com/tag/friendship/. This
      5 min read

    • How to get Scrapy Output File in XML File?
      Prerequisite: Implementing Web Scraping in Python with Scrapy Scrapy provides a fast and efficient method to scrape a website. Web Scraping is used to extract the data from websites. In Scrapy we create a spider and then use it to crawl a website. In this article, we are going to extract population
      2 min read

    • Scraping a JSON response with Scrapy
      Scrapy is a popular Python library for web scraping, which provides an easy and efficient way to extract data from websites for a variety of tasks including data mining and information processing. In addition to being a general-purpose web crawler, Scrapy may also be used to retrieve data via APIs.
      2 min read

    • Logging in Scrapy
      Scrapy is a fast high-level web crawling and scraping framework written in Python used to crawl websites and extract structured data from their pages. It can be used for many purposes, from data mining to monitoring and automated testing. As developers, we spend most of our time debugging than writi
      4 min read

    Appliaction And Projects

    • How to use Scrapy to parse PDF pages online?
      Prerequisite: Scrapy, PyPDF2, URLLIB In this article, we will be using Scrapy to parse any online PDF without downloading it onto the system. To do that we have to use the PDF parser or editor library of Python know as PyPDF2.  PyPDF2 is a pdf parsing library of python, which provides various method
      3 min read

    • How to download Files with Scrapy ?
      Scrapy is a fast high-level web crawling and web scraping framework used to crawl websites and extract structured data from their pages. It can be used for a wide range of purposes, from data mining to monitoring and automated testing. In this tutorial, we will be exploring how to download files usi
      8 min read

    • Automated Website Scraping using Scrapy
      Scrapy is a Python framework for web scraping on a large scale. It provides with the tools we need to extract data from websites efficiently, processes it as we see fit, and store it in the structure and format we prefer. Zyte (formerly Scrapinghub), a web scraping development and services company,
      5 min read

    • Writing Scrapy Python Output to JSON file
      In this article, we are going to see how to write scrapy output into a JSON file in Python. Using  scrapy command-line shell This is the easiest way to save data to JSON is by using the following command: scrapy crawl <spiderName> -O <fileName>.json This will generate a file with a provi
      2 min read

    • Pagination using Scrapy - Web Scraping with Python
      Pagination using Scrapy. Web scraping is a technique to fetch information from websites. Scrapy is used as a Python framework for web scraping. Getting data from a normal website is easier, and can be just achieved by just pulling the HTML of the website and fetching data by filtering tags. But what
      3 min read

    • Email Id Extractor Project from sites in Scrapy Python
      Scrapy is open-source web-crawling framework written in Python used for web scraping, it can also be used to extract data for general-purpose. First all sub pages links are taken from the main page and then email id are scraped from these sub pages using regular expression.  This article shows the e
      8 min read

    • Scraping Javascript Enabled Websites using Scrapy-Selenium
      Scrapy-selenium is a middleware that is used in web scraping. scrapy do not support scraping modern sites that uses javascript frameworks and this is the reason that this middleware is used with scrapy to scrape those modern sites.Scrapy-selenium provide the functionalities of selenium that help in
      4 min read

    • How to use Scrapy Items?
      In this article, we will scrape Quotes data using scrapy items, from the webpage https://quotes.toscrape.com/tag/reading/. The main objective of scraping, is to prepare structured data, from unstructured resources. Scrapy Items are wrappers around, the dictionary data structures. Code can be written
      9 min read

    • How To Follow Links With Python Scrapy ?
      In this article, we will use Scrapy, for scraping data, presenting on linked webpages, and, collecting the same. We will scrape data from the website 'https://quotes.toscrape.com/'. Creating a Scrapy Project Scrapy comes with an efficient command-line tool, also called the 'Scrapy tool'. Commands ar
      8 min read

    • Difference between BeautifulSoup and Scrapy crawler
      Web scraping is a technique to fetch data from websites. While surfing on the web, many websites don’t allow the user to save data for personal use. One way is to manually copy-paste the data, which both tedious and time-consuming. Web Scraping is the automation of the data extraction process from w
      3 min read

    • Python - How to create an ARP Spoofer using Scapy?
      ARP spoofing is a malicious attack in which the hacker sends falsified ARP in a network. Every node in a connected network has an ARP table through which we identify the IP address and the MAC address of the connected devices. What aim to send an ARP broadcast to find our desired IP which needs to b
      6 min read

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences