Introduction
In this tutorial, you'll learn how to use a simple Python script to compare smartphone prices and find the best Memorial Day deals. This practical skill will help you identify when phones are on sale, saving you money on your next device purchase. We'll create a basic web scraper that checks price comparisons for popular smartphones, which is a useful skill for anyone looking to shop smartly for tech gadgets.
Prerequisites
Before starting this tutorial, you'll need:
- A computer with internet access
- Python 3.6 or higher installed
- Basic understanding of how to open a command terminal
- Access to a text editor (like VS Code, Sublime Text, or even Notepad)
Step-by-Step Instructions
Step 1: Set Up Your Python Environment
Install Required Python Packages
First, you need to install the necessary Python packages. Open your command terminal and type:
pip install requests beautifulsoup4
This command installs two essential packages: requests for making web requests and beautifulsoup4 for parsing HTML content. These tools will help us scrape price information from websites.
Step 2: Create Your Python Script File
Open Your Text Editor
Open your preferred text editor and create a new file. Save it as phone_deal_finder.py. This will be our main script for finding deals.
Step 3: Write the Basic Script Structure
Import Required Libraries
At the top of your Python file, add these import statements:
import requests
from bs4 import BeautifulSoup
import time
The requests library will help us fetch web pages, BeautifulSoup will parse the HTML, and time will help us add delays between requests to avoid overwhelming servers.
Step 4: Create a Function to Fetch Phone Prices
Define Your Price Checking Function
Add this function to your script:
def get_phone_price(phone_name, website_url):
try:
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'}
response = requests.get(website_url, headers=headers)
soup = BeautifulSoup(response.content, 'html.parser')
# This is a simplified example - real implementation would need to target specific elements
price_element = soup.find('span', {'class': 'price'})
if price_element:
return price_element.text.strip()
else:
return 'Price not found'
except Exception as e:
return f'Error: {str(e)}'
This function attempts to fetch a webpage and extract price information. The User-Agent header helps us appear as a regular browser to avoid being blocked by websites.
Step 5: Add Sample Phone Data
Create Your Phone Database
Add this data structure to your script:
phones = [
{'name': 'iPhone 14', 'url': 'https://example-store.com/iphone14'},
{'name': 'Samsung Galaxy S23', 'url': 'https://example-store.com/s23'},
{'name': 'Google Pixel 7', 'url': 'https://example-store.com/pixel7'},
{'name': 'iPhone 13', 'url': 'https://example-store.com/iphone13'},
{'name': 'Samsung Galaxy S22', 'url': 'https://example-store.com/s22'}
]
This list contains popular phones and their corresponding store URLs. In a real implementation, you'd need to find the actual URLs for each phone's page.
Step 6: Implement the Main Comparison Logic
Loop Through Phones and Display Results
Add this code to your script:
def check_deals():
print('Checking Memorial Day deals...')
print('=' * 50)
for phone in phones:
price = get_phone_price(phone['name'], phone['url'])
print(f'{phone["name"]}: {price}')
time.sleep(1) # Be respectful to servers
print('=' * 50)
print('Deal checking complete!')
# Run the deal checker
if __name__ == '__main__':
check_deals()
This function loops through each phone in our database, fetches its price, and displays the results. The time.sleep(1) ensures we don't make requests too quickly, which could get our IP blocked.
Step 7: Run Your Deal Finder
Execute Your Script
Save your file and open your command terminal. Navigate to the directory where you saved phone_deal_finder.py, then run:
python phone_deal_finder.py
You should see output showing the prices of different phones. Note that this is a simplified example - real price scraping requires targeting specific HTML elements that contain actual pricing information.
Step 8: Improve Your Script with Better Price Parsing
Enhance the Price Extraction Logic
For a more robust solution, you'd want to customize the price extraction for each website. Here's an improved version:
def get_phone_price_enhanced(phone_name, website_url):
try:
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'}
response = requests.get(website_url, headers=headers)
soup = BeautifulSoup(response.content, 'html.parser')
# Different websites have different price classes - adjust accordingly
price_selectors = [
'span.price',
'div.price',
'p.price',
'[data-testid="price"]',
'.product-price'
]
for selector in price_selectors:
price_element = soup.select_one(selector)
if price_element:
return price_element.text.strip()
return 'Price not found'
except Exception as e:
return f'Error: {str(e)}'
This enhanced function tries multiple possible HTML selectors to find the price, increasing the chance of successfully extracting pricing information.
Step 9: Add Deal Alerts
Implement Price Comparison Logic
Add this function to compare current prices with previous ones:
def compare_prices(current_prices, previous_prices):
print('\nPrice Comparison:')
print('-' * 30)
for phone in current_prices:
if phone in previous_prices:
current = current_prices[phone]
previous = previous_prices[phone]
if current < previous:
print(f'{phone}: Price dropped! {previous} → {current}')
elif current > previous:
print(f'{phone}: Price increased! {previous} → {current}')
else:
print(f'{phone}: Price unchanged')
else:
print(f'{phone}: New deal found! {current_prices[phone]}')
This function helps you track price changes over time, showing when deals are actually getting better or worse.
Step 10: Test Your Complete Script
Run Your Full Deal Finding Program
When you run your complete script, it will:
- Fetch price information from various smartphone retailers
- Display current deals and prices
- Help you identify which phones are on sale
- Allow you to track price changes over time
This tutorial gives you a foundation for building smart shopping tools. You can expand it by adding more phone models, different retailers, or even email alerts for price drops.
Summary
In this tutorial, you've learned how to create a basic smartphone price comparison tool using Python. You've installed required packages, built a script that fetches and displays phone prices, and implemented logic to track price changes. This skill helps you make informed decisions when shopping for devices, especially during sales events like Memorial Day. While this example uses simplified web scraping, it demonstrates the core concepts of how to build tools that help you find the best deals on technology purchases.



