How to Convert Scrapy item to JSON?
Last Updated :
20 Jul, 2022
Prerequisite:
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 further processing to pipelines. In pipelines, these items will be converted to JSON data, and we can either print it or can save it in another file. Hence, we can retrieve JSON data out of web scraped data.
Initializing Directory and Setting Up Project
Let's first create a scrapy project. For that make sure that Python and PIP is installed in the system. Then run the below-given commands one-by-one to create a scrapy project similar to the one which we will be using in this article.
- Let's first create a virtual environment in a folder named GFGScrapy and activate that virtual environment there.
# To create a folder named GFGScrapy
mkdir GFGScrapy
cd GFGScrapy
# making virtual env there
virtualenv
cd scripts
# activating it
activate
cd..
Hence, after running all these commands we will get the output as shown:

- Now it's time to create a scrapy project. For that Make sure that scrapy is installed in the system or not. If not installed install it using the below-given command.
Syntax:
pip install scrapy
Now to create a scrapy project use the below-given command and also create a spider.
scrapy startproject scrapytutorial //project name is scrapytutorial
cd scrapytutorial
scrapy genspider spider_to_crawl https://quotes.toscrape.com/
//The link above mentions the website where we are going to crawl the spider.
Once you have created a scrapy project using pip installer, then the output of the project directory looks like the one given in the image. (Please refer to this if you want to know more about a scrapy project and get familiar with it).

The directory structure consists of the following path (sample)
C://<project-name>/<project-name>
In the above image, the project name is scrapytutorial and it has many files inside it as shown.
The files we are interested in are spider_to_crawl.py file (where we used to describe the methods for our spiders) and pipelines.py file where we will be describing components that will handle our further data processing which is to be done with the scraped data. In simple terms, this file is used to describe the methods which are used for further operations on data. The third most important file is settings.py file where we will be registering our components (created in pipelines,.py file) orderly. The next most important file is items.py file. This file is used to describe the form or dictionary structure in which data will flow from spider_to_crawl to pipelines.py file. Here we will be giving some keys which will be present in each item.
Let's have a look at our spider_to_crawl.py file present inside our spiders folder. This is the file where we are writing the URL where our spider has to crawl and also a method named as parse() which is used to describe what should be done with the data scraped by the spider.
This file is automatically generated by "scrapy genspider" command used above. The file is named after the spider's name. Below given is the default file generated.

Note that we made some changes in the above default file i.e. commented out allowed_domains line and also we made some changes in the strat_urls (removed "http://").
Converting scrapy to JSON
Pipelines are methods by which we can convert or modify or store items of scraped data. Hence, let's first talk about some of its components.
A look to the default Pipelines.py file is shown below:

For performing different operations on items we have to declare a separated component( classes in the file) which consists of various methods, used for performing operations. The pipelines file in default has a class named after the project name. We can also create our own classes to write what operations they have to perform.
Each component of the pipelines.py file is consisting of one default method named as process_item().
Syntax:
process_item( self, item, spider):
This method intakes three variables one is a reference to self-object, another is the item of scraped data send by the spider and the third is the spider itself. This method is used to modify or store the data items that are scraped by the spider. We have to mention the way how the received item packets are to be modified in this method only.
This is the default method which is always called inside the class of pipelines.py file.
Apart from these, we can also create our own methods that can be used to modify or make other changes to data items. Hence since we have to convert our scraped data to JSON format, so we are required to have a component(class) that would do our respective work. But before that, we have to perform two main things.
1) First, we have to register the name of the pipeline component in our settings.py file. The syntax is given below.
Syntax:
ITEM_PIPELINES = {
myproject.pipelines.component : <priority number>
#many other components
}
Here the priority number is the order in which the components will be called by the scrapy.
Hence, for the above project, the below-given format will be applied.
ITEM_PIPELINES = {
'scrapytutorial.pipelines.ScrapytutorialPipeline': 300,
}
2) Another thing that we have to perform is to declare the format of the item which we have to use to pass our data to the pipeline. So for that, we will be using our items.py file.
The below-given code creates an item with one key variable named as "Quote" in our items.py file. Then we have to import this file in our spider_to_crawl.py file(shown in example).
Python3
# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html
import scrapy
class ScrapytutorialItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
Quote = scrapy.Field() # only one field that it of Quote.
The above code creates Items with only one key, we can create items with many keys.
Now since we have seen how to implement components in pipelines.py file and how settings are done and items are declared. Now we are ready to have an example in which we will be converting our scraped data items to JSON format. To convert the data in JSON format we will be using the JSON library of python along with its dumps property. The idea is that we will get the scraped data in pipelines.py file, and then we will open a file and write all the JSON data in it. So methods named :
- open_spider() will be called to open the file (result.json) when spider starts crawling.
- close_spider() will be called to close the file when spider is closed and scraping is over.
- process_item() will always be called (since it is default) and will be mainly responsible to convert the data to JSON format and print the data to the file. We will be using the concept of python web frameworks, i.e. how they convert backend retrieved data to JSON and other formats.
Hence, the code in our pipelines.py looks like:
Python3
from itemadapter import ItemAdapter
import json # Json package of python module.
class ScrapytutorialPipeline:
def process_item(self, item, spider): # default method
# calling dumps to create json data.
line = json.dumps(dict(item)) + "\n"
# converting item to dict above, since dumps only intakes dict.
self.file.write(line) # writing content in output file.
return item
def open_spider(self, spider):
self.file = open('result.json', 'w')
def close_spider(self, spider):
self.file.close()
Our spider_to_crawl.py looks like
Python3
import scrapy
from ..items import ScrapytutorialItem
class SpiderToCrawlSpider(scrapy.Spider):
name = 'spider_to_crawl'
start_urls = ['https://quotes.toscrape.com/']
def parse(self, response):
# creating items dictionary
items = ScrapytutorialItem()
Quotes_all = response.xpath('//div/div/div/span[1]')
# These paths are based on the selectors
for quote in Quotes_all: #extracting data
items['Quote'] = quote.css('::text').extract()
yield items
Our settings.py file looks like:

Our items.py file looks like

After using the command "scrapy crawl spider_to_crawl", The below given steps are going to take place.
- The spider is crawled due to which result.json file is created. Now the spider scrapes the web page and collect the data in Quotes_all Variable. Then each data is extracted from the variable and is passed to the item declared in the file as the value of the key i.e. Quote. The at last in the yield we are calling pipelines.py file for further processing.
- We are receiving item variable from spider in pipelines.py file which is than converted to JSON using dumps method and then the output is written in the opened file.
- The file is than closed, and we can see the output.

Output:

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
Scrapy Basics
Scrapy - Command Line ToolsPrerequisite: 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 LoadersIn 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 PipelineScrapy 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 - SelectorsScrapy 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 - ShellScrapy 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 - SpidersScrapy 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 exportsScrapy 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 ExtractorsIn 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 - SettingsScrapy 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-mailPrerequisites: 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 - ExceptionsPython-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
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 ScrapyIn 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
6 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 ScrapyScrapy 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 ScrapyScrapy 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
3 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 ScrapyScrapy 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 fileIn 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 PythonPagination 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 PythonScrapy 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-SeleniumScrapy-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
9 min read
Difference between BeautifulSoup and Scrapy crawlerWeb 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