Extracting Amazon Product Data with Python

Not long ago, I worked on a project where I had to extract product data from Amazon. It was my first time doing web scraping, and I learned a lot along the way. In this post, I’ll share the techniques that worked for me on one of the biggest e-commerce sites out there.

Sketch of an Amazon product page with the product title, star rating, review count, price, description and categories

The Tech Stack

  • Python: one of the best languages for working with data.
  • Selenium: a browser automation tool that can load and interact with dynamic pages.
  • BeautifulSoup: a library for parsing and searching HTML.

Things to Keep in Mind

Amazon Is Good at Spotting and Blocking Bots

Amazon detects bots mainly by the IP address they come from, whether that’s your home connection or a cloud provider. That’s why sending plain HTTP requests for product pages isn’t the easiest option.

If you go that route, you’ll need to rotate the User-Agent header (which tells the site what browser and operating system the request comes from), or even use a proxy service. Otherwise, Amazon will probably block your address once it sees repeated requests for the same products.

Sketch of three bots sending requests to Amazon.com, with the requests blocked

This is where Selenium helps. It drives a real browser, and each extraction runs in a new browser session, which looks like regular traffic to Amazon.

Product Pages Don’t All Look the Same

You’ll need a few checks to make sure the data you scrape is accurate. A single section, like the product categories, can show up in two different layouts. A couple of if statements are enough to handle that.

Sketch of the same categories shown two ways: as a bulleted list and as a table

Your Bot May Need to Wait

Some important information, like whether an item is in stock, only appears once the page has fully loaded and its JavaScript has run. You may need to wait a full second or more for each page.

You May Need More Computing Power

Leaving your own computer running for hours isn’t always practical. Running the bot as a scheduled job in the cloud means you don’t have to worry about when and where it runs.

Scraping Product Data

How you package the bot is up to you: a desktop app, a cloud service or a simple script. In this post, I’ll focus on the scraping code and leave the rest to you. If you want to see a full example, mine is a Python desktop app: github.com/andresromerodev/amazon-product-reports (opens in new tab).

Setting Up the Project

Install Selenium and BeautifulSoup with pip:

pip install selenium beautifulsoup4

Since version 4.6, Selenium downloads the right browser driver for you, so you don’t need to install ChromeDriver yourself. Create a driver and you’re ready to go. This is the starting point of your bot:

import re
import time

from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

options = webdriver.ChromeOptions()
# options.add_argument('--headless=new')  # Uncomment on a server with no screen

driver = webdriver.Chrome(options=options)

If you plan to run it on a cloud server without a screen, turn on headless mode as shown in the comment.

Setting the Delivery Location

Prices and availability depend on where the product ships. I only needed data for New York City, but you can use any ZIP code, or several. Start from Amazon’s home page and set the location like this:

NYC_ZIP_CODE = '10001'
LOCATION_INPUT_ID = 'GLUXZipUpdateInput'
LOCATION_POPOVER_ID = 'nav-global-location-popover-link'
AMAZON_US_URL = 'https://www.amazon.com/?language=en_US'

def set_delivery_to_nyc():
    driver.get(AMAZON_US_URL)

    driver.find_element(By.ID, LOCATION_POPOVER_ID).click()

    location_field = WebDriverWait(driver, 30).until(
        EC.element_to_be_clickable((By.ID, LOCATION_INPUT_ID))
    )
    location_field.click()
    location_field.send_keys(NYC_ZIP_CODE)
    location_field.send_keys(Keys.RETURN)

Loading a Product Page

As I mentioned, the page sections can vary. The selectors below worked as of 2023.

You can open any product with the URL https://www.amazon.com/dp/PRODUCT_CODE.

You need both tools here. Selenium loads the full page, including the content that JavaScript adds after the initial HTML. Once it’s loaded, you hand the final HTML to BeautifulSoup to pull out the data.

url = 'https://www.amazon.com/dp/' + 'ABC123'

driver.get(url)
time.sleep(1)  # Give the page's JavaScript time to finish

soup = BeautifulSoup(driver.page_source, 'html.parser')

Extracting Each Field

Here are the snippets I used for the main product fields. Every field can be missing, so each one falls back to an empty value instead of crashing. Some of them use this small helper to turn text like “1,234 ratings” into a number:

def to_int(text):
    digits = ''.join(c for c in text if c.isdigit())
    return int(digits) if digits else 0

Product Title

If a page has no title, the product is no longer available. Amazon shows its “dog page” (the 404 page with dog photos) instead.

title_tag = soup.find(id='productTitle')
title = title_tag.get_text(strip=True) if title_tag else None

Stock

in_stock = bool(soup.select('#availability .a-color-success'))
stock = 'Available' if in_stock else 'Unavailable'

Q&A Count

qa_tag = soup.select_one('#askATFLink span')
qa_count = to_int(qa_tag.get_text()) if qa_tag else 0

Star Rating

stars_tag = soup.select_one('i[class*="a-icon-star"] span')
stars = float(stars_tag.get_text().split(' ')[0].replace(',', '.')) if stars_tag else 0.0

Review Count

reviews_tag = soup.select_one('#acrCustomerReviewText')
review_count = to_int(reviews_tag.get_text()) if reviews_tag else 0

Best Sellers Rank and Categories

The rank and the categories live in the same place, which is either a bulleted list or a table depending on the page. Each entry looks like “#1,234 in Kitchen & Dining”, so one regular expression gets both the rank and its category.

RANK_REGEX = r'#([\d,]+) in ([^(#]+)'

details = soup.find(id='detailBulletsWrapper_feature_div')
if not details or 'Best Sellers Rank' not in details.get_text():
    # Some pages show the details in a table instead of a list
    details = soup.find(id='productDetails_detailBullets_sections1')

ranks = []
if details:
    for rank, category in re.findall(RANK_REGEX, details.get_text(' ', strip=True)):
        ranks.append((to_int(rank), category.strip()))

Coupons

coupon_tag = soup.find(id='vpcButton')
match = re.search(r'\d+%|\$\d+(?:\.\d+)?', coupon_tag.get_text()) if coupon_tag else None
coupon = match.group() if match else ''

Ships From

ships_from_tag = soup.select_one('#tabular-buybox-truncate-0 .tabular-buybox-text')
ships_from = ships_from_tag.get_text(strip=True) if ships_from_tag else ''

Sold By

sold_by_tag = soup.find(id='sellerProfileTriggerId')
sold_by = sold_by_tag.get_text(strip=True) if sold_by_tag else ''

Wrapping Up

I hope this saves you some time, whether it’s for a personal experiment or because you work with Amazon product data often.

Thanks for reading!

All posts