NYC Data Science Academy| Blog
Bootcamps
Lifetime Job Support Available Financing Available
Bootcamps
Data Science with Machine Learning Flagship ๐Ÿ† Data Analytics Bootcamp Artificial Intelligence Bootcamp New Release ๐ŸŽ‰
Free Lesson
Intro to Data Science New Release ๐ŸŽ‰
Find Inspiration
Find Alumni with Similar Background
Job Outlook
Occupational Outlook Graduate Outcomes Must See ๐Ÿ”ฅ
Alumni
Success Stories Testimonials Alumni Directory Alumni Exclusive Study Program
Courses
View Bundled Courses
Financing Available
Bootcamp Prep Popular ๐Ÿ”ฅ Data Science Mastery Data Science Launchpad with Python View AI Courses Generative AI for Everyone New ๐ŸŽ‰ Generative AI for Finance New ๐ŸŽ‰ Generative AI for Marketing New ๐ŸŽ‰
Bundle Up
Learn More and Save More
Combination of data science courses.
View Data Science Courses
Beginner
Introductory Python
Intermediate
Data Science Python: Data Analysis and Visualization Popular ๐Ÿ”ฅ Data Science R: Data Analysis and Visualization
Advanced
Data Science Python: Machine Learning Popular ๐Ÿ”ฅ Data Science R: Machine Learning Designing and Implementing Production MLOps New ๐ŸŽ‰ Natural Language Processing for Production (NLP) New ๐ŸŽ‰
Find Inspiration
Get Course Recommendation Must Try ๐Ÿ’Ž An Ultimate Guide to Become a Data Scientist
For Companies
For Companies
Corporate Offerings Hiring Partners Candidate Portfolio Hire Our Graduates
Students Work
Students Work
All Posts Capstone Data Visualization Machine Learning Python Projects R Projects
Tutorials
About
About
About Us Accreditation Contact Us Join Us FAQ Webinars Subscription An Ultimate Guide to
Become a Data Scientist
    Login
NYC Data Science Acedemy
Bootcamps
Courses
Students Work
About
Bootcamps
Bootcamps
Data Science with Machine Learning Flagship
Data Analytics Bootcamp
Artificial Intelligence Bootcamp New Release ๐ŸŽ‰
Free Lessons
Intro to Data Science New Release ๐ŸŽ‰
Find Inspiration
Find Alumni with Similar Background
Job Outlook
Occupational Outlook
Graduate Outcomes Must See ๐Ÿ”ฅ
Alumni
Success Stories
Testimonials
Alumni Directory
Alumni Exclusive Study Program
Courses
Bundles
financing available
View All Bundles
Bootcamp Prep
Data Science Mastery
Data Science Launchpad with Python NEW!
View AI Courses
Generative AI for Everyone
Generative AI for Finance
Generative AI for Marketing
View Data Science Courses
View All Professional Development Courses
Beginner
Introductory Python
Intermediate
Python: Data Analysis and Visualization
R: Data Analysis and Visualization
Advanced
Python: Machine Learning
R: Machine Learning
Designing and Implementing Production MLOps
Natural Language Processing for Production (NLP)
For Companies
Corporate Offerings
Hiring Partners
Candidate Portfolio
Hire Our Graduates
Students Work
All Posts
Capstone
Data Visualization
Machine Learning
Python Projects
R Projects
About
Accreditation
About Us
Contact Us
Join Us
FAQ
Webinars
Subscription
An Ultimate Guide to Become a Data Scientist
Tutorials
Data Analytics
  • Learn Pandas
  • Learn NumPy
  • Learn SciPy
  • Learn Matplotlib
Machine Learning
  • Boosting
  • Random Forest
  • Linear Regression
  • Decision Tree
  • PCA
Interview by Companies
  • JPMC
  • Google
  • Facebook
Artificial Intelligence
  • Learn Generative AI
  • Learn ChatGPT-3.5
  • Learn ChatGPT-4
  • Learn Google Bard
Coding
  • Learn Python
  • Learn SQL
  • Learn MySQL
  • Learn NoSQL
  • Learn PySpark
  • Learn PyTorch
Interview Questions
  • Python Hard
  • R Easy
  • R Hard
  • SQL Easy
  • SQL Hard
  • Python Easy
Data Science Blog > Student Works > Tutorial: How To Scrape Amazon Using Python Scrapy

Tutorial: How To Scrape Amazon Using Python Scrapy

Sandra Moraes
Posted on Oct 17, 2019
Amazon is a tough website to scrape for Beginners. This blog post is a step by step guide to scraping Amazon using  Python Scrapy .
 
What is Scrapy ?
 Prerequisites:
Scrapy 1.1.1
 
Scrapy is an application framework for crawling web sites and extracting structured/unstructured data which can be used for a wide range of applications such as data mining, information processing or historical archival.
 
As we all know, this is the age of โ€œDataโ€. Data is everywhere, and every organisation wants to work with Data and take its business to a higher level. In this scenario Scrapy plays a vital role to provide Data to these organisations so that they can use it in wide range of applications. Scrapy is not only able to scrap data from websites, but it is able to scrap data from web services. For example Amazon API, Twitter/Facebook API as well.
 
 
How to install Scrapy ?
 
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 install python libraries, and its dependencies automatically. It is better to install pip according to system OS, and then try to follow the standard way for 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 which helps to structure html tree, as web pages use html hierarchy to organise 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 which 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 which 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 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 customise the behaviour 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 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 scraped 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.
 
 
Letโ€™s Scrape Amazon Web Page
 
To understand how scrapy works and how can we use it in practical scenarios, lets take an example in which we will scrap data related to a product , for example product name, its price, category and its availability on amazon.com website. Lets name this project amazon. As discussed earlier, before doing anything lets 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,
 
  1.  Update items.py with fields which we want to extract. Here for example product name, category, price etc.
  2.  Create a new Spider in which we need to define the necessary elements, like allowed_domains, start_urls, parse method to parse  response object.
  3. Update pipelines.py for further data processing.
 
Lets start with items.py first. Below is the code which describes multiple required fields in the framework.
 
 
  # -*- coding: utf-8 -*-
   
  # Define here the models for your scraped items
  #
  # See documentation in:
  # http://doc.scrapy.org/en/latest/topics/items.html
   
  import scrapy
   
  class AmazonItem(scrapy.Item):
  # define the fields for your item here like:
  product_name = scrapy.Field()
  product_sale_price = scrapy.Field()
  product_category = scrapy.Field()
  product_original_price = scrapy.Field()
  product_availability = scrapy.Field()
view rawamazon_item hosted with โค by GitHub
Now to create Spiders, we can have different options.
1) We can create simple Python class in spiders directory and import essential modules to it
2) We can use default utility which is provided by scrapy framework itself.
Here we are going to use the default utility called genspider to create Spiders in framework. It will automatically create a class with default template in spiders directory.
 
scrapy genspider AmazonProductSpider

 

 
In newly created AmazonProductSpider, we need to define its name,  URLs and possible domains to scrap data. We also need to implement 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 yield 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 scrap data from this domain and start_urls are pointing to the specific pages of the same domain.
 
 
  # -*- coding: utf-8 -*-
  import scrapy
  from amazon.items import AmazonItem
   
  class AmazonProductSpider(scrapy.Spider):
  name = "AmazonDeals"
  allowed_domains = ["amazon.com"]
   
  #Use working product URL below
  start_urls = [
  "http://www.amazon.com/dp/B0046UR4F4", "http://www.amazon.com/dp/B00JGTVU5A",
  "http://www.amazon.com/dp/B00O9A48N2", "http://www.amazon.com/dp/B00UZKG8QU"
  ]
   
  def parse(self, response):
  items = AmazonItem()
  title = response.xpath('//h1[@id="title"]/span/text()').extract()
  sale_price = response.xpath('//span[contains(@id,"ourprice") or contains(@id,"saleprice")]/text()').extract()
  category = response.xpath('//a[@class="a-link-normal a-color-tertiary"]/text()').extract()
  availability = response.xpath('//div[@id="availability"]//text()').extract()
  items['product_name'] = ''.join(title).strip()
  items['product_sale_price'] = ''.join(sale_price).strip()
  items['product_category'] = ','.join(map(lambda x: x.strip(), category)).strip()
  items['product_availability'] = ''.join(availability).strip()
  yield items
view rawamazon_parser_scrapy hosted with โค by GitHub
In parse method,  an item object is defined and is filled with required information using xpath utility of response object. xpath is a search function which is used to find elements in html tree structure. Lastly lets 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 as 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 which scrapy generates for users.
 
 
  # -*- coding: utf-8 -*-
  # Define your item pipelines here
  # Don't forget to add your pipeline to the ITEM_PIPELINES setting
  # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
   
  class AmazonPipeline(object):
  def process_item(self, item, spider):
  return item
view rawamazon_pipeline hosted with โค by GitHub
Pipeline classes implement process_item method which is called each and every time whenever items is being yielded by a Spider. It takes 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 settings.py module so that scrapy can call an item object after parsing from spiders.
 
  # Configure item pipelines
  # See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html
  ITEM_PIPELINES = {
  'amazon.pipelines.AmazonPipeline': 300,
  }
view rawamazon_pipeline hosted with โค by GitHub
Let us give numbers from 1-1000 to pipeline classes as a value which 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 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.
 
 
  [
  {"product_category": "Electronics,Computers & Accessories,Data Storage,External Hard Drives", "product_sale_price": "$949.95", "product_name": "G-Technology G-SPEED eS PRO High-Performance Fail-Safe RAID Solution for HD/2K Production 8TB (0G01873)", "product_availability": "Only 1 left in stock."},
  {"product_category": "Electronics,Computers & Accessories,Data Storage,USB Flash Drives", "product_sale_price": "", "product_name": "G-Technology G-RAID with Removable Drives High-Performance Storage System 4TB (Gen7) (0G03240)", "product_availability": "Available from these sellers."},
  {"product_category": "Electronics,Computers & Accessories,Data Storage,USB Flash Drives", "product_sale_price": "$549.95", "product_name": "G-Technology G-RAID USB Removable Dual Drive Storage System 8TB (0G04069)", "product_availability": "Only 1 left in stock."},
  {"product_category": "Electronics,Computers & Accessories,Data Storage,External Hard Drives", "product_sale_price": "$89.95", "product_name": "G-Technology G-DRIVE ev USB 3.0 Hard Drive 500GB (0G02727)", "product_availability": "Only 1 left in stock."}
  ]
view rawamazon_data_output hosted with โค by GitHub
 
If you still have confusion regarding the amazon scraping, try the video tutorial prepared by the best video production company.
 
Ta da! We have successfully covered scraping using scrapy. We have covered most of the stuff related to scrapy and its relatedmodules and also understood how can we can use it independently through an example.
 
Read the full article here: https://blog.datahut.co/tutorial-how-to-scrape-amazon-data-using-python-scrapy/

The skills the authors demonstrated here can be learned through taking Data Science with Machine Learning bootcamp with NYC Data Science Academy.

About Author

Sandra Moraes

View all posts by Sandra Moraes >

Related Articles

Community
Job Search: 6 Proven Tips for Aspiring Data Scientists
Community
Data Science: 5 Must-Have Qualities Of An Online Bootcamp
Data Visualization
This Old House: Using ML to Guide Home Renovations
Data Visualization
Data Analysis: What's in Your (Doctor's) Wallet?
Alumni
Career Day at NYC Data Science Academy, January 15, 2020

Leave a Comment

No comments found.

View Posts by Categories

All Posts 2399 posts
AI 7 posts
AI Agent 2 posts
AI-based hotel recommendation 1 posts
AIForGood 1 posts
Alumni 60 posts
Animated Maps 1 posts
APIs 41 posts
Artificial Intelligence 2 posts
Artificial Intelligence 2 posts
AWS 13 posts
Banking 1 posts
Big Data 50 posts
Branch Analysis 1 posts
Capstone 206 posts
Career Education 7 posts
CLIP 1 posts
Community 72 posts
Congestion Zone 1 posts
Content Recommendation 1 posts
Cosine SImilarity 1 posts
Data Analysis 5 posts
Data Engineering 1 posts
Data Engineering 3 posts
Data Science 7 posts
Data Science News and Sharing 73 posts
Data Visualization 324 posts
Events 5 posts
Featured 37 posts
Function calling 1 posts
FutureTech 1 posts
Generative AI 5 posts
Hadoop 13 posts
Image Classification 1 posts
Innovation 2 posts
Kmeans Cluster 1 posts
LLM 6 posts
Machine Learning 364 posts
Marketing 1 posts
Meetup 144 posts
MLOPs 1 posts
Model Deployment 1 posts
Nagamas69 1 posts
NLP 1 posts
OpenAI 5 posts
OpenNYC Data 1 posts
pySpark 1 posts
Python 16 posts
Python 458 posts
Python data analysis 4 posts
Python Shiny 2 posts
R 404 posts
R Data Analysis 1 posts
R Shiny 560 posts
R Visualization 445 posts
RAG 1 posts
RoBERTa 1 posts
semantic rearch 2 posts
Spark 17 posts
SQL 1 posts
Streamlit 2 posts
Student Works 1687 posts
Tableau 12 posts
TensorFlow 3 posts
Traffic 1 posts
User Preference Modeling 1 posts
Vector database 2 posts
Web Scraping 483 posts
wukong138 1 posts

Our Recent Popular Posts

AI 4 AI: ChatGPT Unifies My Blog Posts
by Vinod Chugani
Dec 18, 2022
Meet Your Machine Learning Mentors: Kyle Gallatin
by Vivian Zhang
Nov 4, 2020
NICU Admissions and CCHD: Predicting Based on Data Analysis
by Paul Lee, Aron Berke, Bee Kim, Bettina Meier and Ira Villar
Jan 7, 2020

View Posts by Tags

#python #trainwithnycdsa 2019 2020 Revenue 3-points agriculture air quality airbnb airline alcohol Alex Baransky algorithm alumni Alumni Interview Alumni Reviews Alumni Spotlight alumni story Alumnus ames dataset ames housing dataset apartment rent API Application artist aws bank loans beautiful soup Best Bootcamp Best Data Science 2019 Best Data Science Bootcamp Best Data Science Bootcamp 2020 Best Ranked Big Data Book Launch Book-Signing bootcamp Bootcamp Alumni Bootcamp Prep boston safety Bundles cake recipe California Cancer Research capstone car price Career Career Day ChatGPT citibike classic cars classpass clustering Coding Course Demo Course Report covid 19 credit credit card crime frequency crops D3.js data data analysis Data Analyst data analytics data for tripadvisor reviews data science Data Science Academy Data Science Bootcamp Data science jobs Data Science Reviews Data Scientist Data Scientist Jobs data visualization database Deep Learning Demo Day Discount disney dplyr drug data e-commerce economy employee employee burnout employer networking environment feature engineering Finance Financial Data Science fitness studio Flask flight delay football gbm Get Hired ggplot2 googleVis H20 Hadoop hallmark holiday movie happiness healthcare frauds higgs boson Hiring hiring partner events Hiring Partners hotels housing housing data housing predictions housing price hy-vee Income industry Industry Experts Injuries Instructor Blog Instructor Interview insurance italki Job Job Placement Jobs Jon Krohn JP Morgan Chase Kaggle Kickstarter las vegas airport lasso regression Lead Data Scienctist Lead Data Scientist leaflet league linear regression Logistic Regression machine learning Maps market matplotlib Medical Research Meet the team meetup methal health miami beach movie music Napoli NBA netflix Networking neural network Neural networks New Courses NHL nlp NYC NYC Data Science nyc data science academy NYC Open Data nyc property NYCDSA NYCDSA Alumni Online Online Bootcamp Online Training Open Data painter pandas Part-time performance phoenix pollutants Portfolio Development precision measurement prediction Prework Programming public safety PwC python Python Data Analysis python machine learning python scrapy python web scraping python webscraping Python Workshop R R Data Analysis R language R Programming R Shiny r studio R Visualization R Workshop R-bloggers random forest Ranking recommendation recommendation system regression Remote remote data science bootcamp Scrapy scrapy visualization seaborn seafood type Selenium sentiment analysis sentiment classification Shiny Shiny Dashboard Spark Special Special Summer Sports statistics streaming Student Interview Student Showcase SVM Switchup Tableau teachers team team performance TensorFlow Testimonial tf-idf Top Data Science Bootcamp Top manufacturing companies Transfers tweets twitter videos visualization wallstreet wallstreetbets web scraping Weekend Course What to expect whiskey whiskeyadvocate wildfire word cloud word2vec XGBoost yelp youtube trending ZORI

NYC Data Science Academy

NYC Data Science Academy teaches data science, trains companies and their employees to better profit from data, excels at big data project consulting, and connects trained Data Scientists to our industry.

NYC Data Science Academy is licensed by New York State Education Department.

Get detailed curriculum information about our
amazing bootcamp!

Please enter a valid email address
Sign up completed. Thank you!

Offerings

  • HOME
  • DATA SCIENCE BOOTCAMP
  • ONLINE DATA SCIENCE BOOTCAMP
  • Professional Development Courses
  • CORPORATE OFFERINGS
  • HIRING PARTNERS
  • About

  • About Us
  • Alumni
  • Blog
  • FAQ
  • Contact Us
  • Refund Policy
  • Join Us
  • SOCIAL MEDIA

    ยฉ 2025 NYC Data Science Academy
    All rights reserved. | Site Map
    Privacy Policy | Terms of Service
    Bootcamp Application