Mathew K Analytics

Lesson 3 · Data Science Projects

Biblical Principles in Data Analysis: Scraping and Analyzing Product Prices with Python

What is product price scraping? Why web scraping matters for data mining. Real world uses of product price data. Lesson goal: Learn basic scraping and…

⬇ Download notebookOpen in Colab ↗

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb

Product Price Scraping and Analysis#

  • What is product price scraping?

  • Why web scraping matters for data mining.

  • Real world uses of product price data.

  • Lesson goal: Learn basic scraping and analysis for product prices.

Why Learn Product Price Scraping?#

  • It allows you to collect real world price data quickly.
  • Businesses track competitors using scraped prices.
  • Data scientists use pricing data to find trends.
  • Skills you learn here help in many areas of analytics.
# Always suppress warnings for a cleaner notebook
import warnings; warnings.filterwarnings("ignore")
import numpy as np
np.random.seed(42)

Data setup#

  • Let us grab a sample set of product prices from a test ecommerce site.
  • The site is made for practice scraping and is safe.
  • We load and preview five products including their prices.
# Data setup (Product Price Scraping and Analysis)
import requests
from bs4 import BeautifulSoup
headers = {'User-Agent': 'Mozilla/5.0'}
url = 'https://webscraper.io/test-sites/e-commerce/static/computers/laptops'
html = requests.get(url, headers=headers).text
soup = BeautifulSoup(html, 'html.parser')
items = [(d.select_one('.title').get_text(strip=True), d.select_one('.price').get_text(strip=True)) for d in soup.select('.thumbnail')]
print(items[:5])
[('Packard 255 G2', '$416.99'), ('Aspire E1-510', '$306.99'), ('ThinkPad T540p', '$1178.99'), ('ProBook', '$739.99'), ('ThinkPad X240', '$1311.99')]
# Let us organize those products into a table for analysis
import pandas as pd
df = pd.DataFrame(items, columns=["Product", "Price"])
print(df.shape)
df.head()
(6, 2)
Product Price
0 Packard 255 G2 $416.99
1 Aspire E1-510 $306.99
2 ThinkPad T540p $1178.99
3 ProBook $739.99
4 ThinkPad X240 $1311.99

Data Cleaning: Prices#

  • Our prices are strings with currency symbols.
  • To analyze, we must convert prices to numbers.
  • We will remove symbols and change type.
# Remove currency symbols from Price column
df['Price'] = df['Price'].str.replace('$', '').astype(float)
df.head()
Product Price
0 Packard 255 G2 416.99
1 Aspire E1-510 306.99
2 ThinkPad T540p 1178.99
3 ProBook 739.99
4 ThinkPad X240 1311.99
# Check for missing data (very common in real world scraping)
print(df.isnull().sum())
Product    0
Price      0
dtype: int64

Simple Stats Analysis#

  • Now that prices are numbers, we can ask questions.
  • How many products do we have?
  • What is the most and least expensive product?
  • What is the average price?
# Basic descriptive stats on product prices
print('Number of items:', df.shape[0])
print('Min price:', df['Price'].min())
print('Max price:', df['Price'].max())
print('Mean price:', round(df['Price'].mean(), 2))
Number of items: 6
Min price: 306.99
Max price: 1311.99
Mean price: 756.16
# Find the name of the cheapest and most expensive products
cheapest = df.loc[df['Price'].idxmin()]
expensive = df.loc[df['Price'].idxmax()]
print('Cheapest:', cheapest['Product'], cheapest['Price'])
print('Most Expensive:', expensive['Product'], expensive['Price'])
Cheapest: Aspire E1-510 306.99
Most Expensive: ThinkPad X240 1311.99

Visualizing Product Prices#

  • A simple chart can make price comparison easier.
  • Let us plot all prices as a bar chart.
# Plot a bar chart of product prices
import matplotlib.pyplot as plt
plt.figure(figsize=(10,5))
plt.bar(df['Product'], df['Price'])
plt.xticks(rotation=45, ha='right', fontsize=8)
plt.ylabel('Price (USD)')
plt.title('Product Price Comparison')
plt.tight_layout()
plt.show()
No description has been provided for this image
# Sort products by price from lowest to highest
df_sorted = df.sort_values('Price')
df_sorted.reset_index(drop=True, inplace=True)
df_sorted.head()
Product Price
0 Aspire E1-510 306.99
1 Packard 255 G2 416.99
2 Aspire E1-572G 581.99
3 ProBook 739.99
4 ThinkPad T540p 1178.99
# Filtering: Show only products above $1000
expensive_products = df[df['Price'] > 1000]
expensive_products
Product Price
2 ThinkPad T540p 1178.99
4 ThinkPad X240 1311.99

Mini Exercise: Your Turn#

  • Try filtering for products below $400.
  • What happens if you try $1500?
  • Can you find the product with a price closest to the average?
# Challenge: Find the product closest to the average price
avg_price = df['Price'].mean()
closest = df.iloc[(df['Price'] - avg_price).abs().idxmin()]
print('Product closest to average:', closest['Product'], closest['Price'])
Product closest to average: ProBook 739.99

What You Learned#

  • How to scrape product and price data safely.

  • Simple cleaning to make data usable.

  • Basic analysis and charts for insights.

  • You can build on these steps for more advanced scraping.

  • Like and subscribe for more beginner Python lessons!

# Optional: Let the user enter a price filter using input()
price_cutoff = float(input("Show products above what price? (Enter a number): "))
filtered = df[df['Price'] > price_cutoff]
print(filtered)
          Product    Price
2  ThinkPad T540p  1178.99
3         ProBook   739.99
4   ThinkPad X240  1311.99
 

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.