How To Scrape Amazon Data Using Python Scrapy
Updated: Feb 5, 2021
With a large number of companies providing products, price, review, and other forms of monitoring solutions for Amazon, scraping Amazon is a huge business today. But trying to scrape Amazon data on a large scale is a challenging task, often leading to getting blocked by Amazon’s anti-scraping technology.
Amazon is a tough website to scrape for beginners. Hence, through this blog post, we aim to provide an easy to understand step by step guide on how to scrape Amazon data using Python Scrapy.
What is Scrapy?
Scrapy is an application framework for crawling websites and extracting structured/unstructured data that can be used for a wide range of applications such as data mining, information processing or historical archival.
Scrapy plays a vital role to provide data to organizations so that they can use it in a wide range of applications. Scrapy is not only able to scrap data from websites, but it is able to scrape data from web services. For example Amazon API, Twitter/Facebook API as well.
Prerequisites: Scrapy 1.1.1
How to install Scrapy?
The following are third party softwares and packages which need to be installed in order to install Scrapy in a system.
Python: As Scrapy has been built using Python language, one has to install it first.
pip: pip is a python package manager tool which maintains a package repository and installs python libraries, and its dependencies automatically. It is better to install pip according to system OS, and then try to follow the standard way of installing Scrapy.
lxml: This is an optional package but needs to be installed if one is willing to scrap HTML data. lxml is a python library that helps to structure HTML tree, as web pages use HTML hierarchy to organize information or Data.
One can install Scrapy using pip (which is the canonical way to install Python packages). To install using Scrapy, run:
pip install scrapy
How to get started with Scrapy?
Scrapy is an application framework and it provides many commands to create applications and use them. Before creating an application, one will have to set up a new Scrapy project. Enter a directory where you’d like to store your code and run:
scrapy startproject test_project
This will create a directory with the name of xyz in the same directory with following contents:
test_project/ scrapy.cfg test_project/ __init__.py items.py pipelines.py settings.py spiders/ __init__.py
Scrapy, as an application framework follows a project structure along with Object Oriented style of programming to define items and spiders for overall applications. The project structure which scrapy creates for a user has,
scrapy.cfg: It is a project configuration file which contains information for setting module for the project along with its deployment information.
test_project: It is an application directory with many different files that are actually responsible for running and scraping data from web URLs.
items.py: Items are containers that will be loaded with the scraped data; they work like simple Python dicts. While one can use plain Python dicts with Scrapy, Items provide additional protection against populating undeclared fields, preventing typos. They are declared by creating a scrapy.Item class and defining its attributes as scrapy.Field objects.
pipelines.py: After an item has been scraped by a spider, it is sent to the Item Pipeline which processes it through several components that are executed sequentially. Each item pipeline component is a Python class that has to implement a method called process_item to process scraped items. It receives an item and performs an action on it, also decides if the item should continue through the pipeline or should be dropped and not processed any longer. If it wants to drop an item then it raises DropItem exception to drop it.
settings.py: It allows one to customize the behavior of all Scrapy components, including the core, extensions, pipelines, and spiders themselves. It provides a global namespace of key-value mappings that the code can use to pull configuration values from.
spiders: Spiders is a directory which contains all spiders/crawlers as Python classes. Whenever one runs/crawls any spider then scrapy looks into this directory and tries to find the spider with its name provided by the user. Spiders define how a certain site or a group of sites will be scraped, including how to perform the crawl and how to extract data from their pages.
In other words, Spiders are the place where one defines the custom behavior for crawling and parsing pages for a particular site. Spiders have to define three major attributes i.e start_urls which tells which URLs are to be scrapped, allowed_domains which defines only those domain names which need to scrape and parse is a method which is called when any response comes from lodged requests. These attributes are important because these constitute the base of Spider definitions.
Scrape Amazon Data: How to Scrape an Amazon Web Page
To understand how scrapy works and how can we use it in practical scenarios, let’s take an example in which we will scrap data related to a product, for example, product name, price, category, and its availability on the amazon.com website. Let’s name this project amazon. As discussed earlier, before doing anything let’s start with creating a scrapy project using the command below.
scrapy startproject amazon
This command will create a directory name amazon in the local folder with a structure as defined earlier. Now we need to create three different things to make the scrap process work successfully, they are,
Update items.py with fields which we want to extract. Here for example product name, category, price, etc.
Create a new Spider in which we need to define the necessary elements, like allowed_domains, start_urls, parse method to parse response object.
Update pipelines.py for further data processing.
Let’s start with items.py first. Below is the code which describes multiple required fields in the framework.
Now to create Spiders, we can have different options.
1) We can create a simple Python class in the spiders directory and import essential modules to it.
2) We can use the default utility which is provided by the scrapy framework itself.
Here we are going to use the default utility called genspider to create Spiders in the framework. It will automatically create a class with a default template in the spiders directory.
scrapy genspider AmazonProductSpider
In the newly created AmazonProductSpider, we need to define its name, URLs, and possible domains to scrap data. We also need to implement a parse method where custom commands can be defined for filling item fields and further processing can be done on the response object. This parse method does not return but yields things. Yield in python means that python will start the execution from where it has been stopped last time.
Here is the code for Spider. A name is defined for Spider, which should be unique throughout all the Spiders because scrapy searches for Spiders using its name. allowed_domains is initialized with amazon.com as we are going to scrape data from this domain and start_urls are pointing to the specific pages of the same domain.
In the parse method, an item object is defined and is filled with required information using XPath utility of response object. XPath is a search function that is used to find elements in the HTML tree structure. Lastly let’s yield the items object, so that scrapy can do further processing on it.
Next, after scraping data, scrapy calls Item pipelines to process them. These are called Pipeline classes and we can use these classes to store data in a file or database or in any other way. It is a default class like Items that scrapy generates for users.
Pipeline classes implement the process_item method which is called each and every time whenever items are being yielded by a Spider. It takes the item and spider class as arguments and returns a dict object. So for this example, we are just returning item dict as it is.
Before using pipeline classes one has to enable them in the settings.py module so that scrapy can call an item object after parsing from spiders.
Let us give numbers from 1-1000 to pipeline classes as a value that defines the order in which these classes will be called by scrapy framework. This value defines which pipeline class should be run first by scrapy.
Now, after all the set up is done, we need to start scrapy and call Spider so that it can start sending requests and accept response objects.
We can call spider through its name as it will be unique and scrapy can easily search for it.
scrapy crawl AmazonDeals
If we want to store item fields in a file then we can write code in pipeline classes else we can define filename at the time of calling the spider so that scrapy can automatically push the return objects from pipeline classes to the given file.
scrapy crawl AmazonDeals -o items.json
So the above command will save the item objects in the items.json file. As we are returning item objects in pipeline class, scrapy will automatically store these item objects into items.json. Here is the output of this process.
We have successfully covered scraping using scrapy. We have covered most of the stuff related to scrapy and its related modules and also understood how can we can use it independently through an example.
Here are a few more references which can be helpful in knowing more about Scrapy.
Did you find this tutorial helpful? Let us know in the comments below.
Datahut helps organizations scrape Amazon data on a large scale. Contact us for your Amazon Data scraping needs.