Certainly! Below is a complete Python scraper that extracts product information from the specified URL on armedangels.com. This script uses the requests library to fetch the page content and BeautifulSoup from the bs4 library to parse the HTML. It extracts various details such as product name, price, SKU, product URL, image URLs, and available sizes. Finally, it saves the extracted data into a CSV file.
Prerequisites
-
Python 3.x: Ensure you have Python 3 installed on your machine. You can download it from here.
-
Required Libraries: Install the necessary Python libraries using pip:
pip install requests beautifulsoup4 pandas
Scraper Implementation
import requests
from bs4 import BeautifulSoup
import pandas as pd
import time
import random
# Define headers to mimic a real browser request
HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
" AppleWebKit/537.36 (KHTML, like Gecko)"
" Chrome/114.0.0.0 Safari/537.36",
"Accept-Language": "en-US,en;q=0.9",
}
def get_soup(url):
"""
Fetches the content of the URL and returns a BeautifulSoup object.
"""
try:
response = requests.get(url, headers=HEADERS)
response.raise_for_status() # Raise an error for bad status codes
return BeautifulSoup(response.text, 'html.parser')
except requests.RequestException as e:
print(f"Error fetching {url}: {e}")
return None
def extract_product_info(product_div):
"""
Extracts product information from a single product div.
"""
# Initialize a dictionary to store product data
product_data = {}
try:
# Extract SKU
sku_tag = product_div.find('meta', {'itemprop': 'sku'})
product_data['SKU'] = sku_tag['content'] if sku_tag else None
# Extract product link and name
product_link_tag = product_div.find('a', class_='product-info-link')
if product_link_tag:
product_data['Product Name'] = product_link_tag.get('title', '').strip()
product_data['Product URL'] = product_link_tag.get('href', '').strip()
else:
product_data['Product Name'] = None
product_data['Product URL'] = None
# Extract price
price_tag = product_div.find('p', class_='product-price')
product_data['Price'] = price_tag.text.strip() if price_tag else None
# Extract image URLs
image_tags = product_div.find_all('img', class_='product-image')
image_urls = [img['src'] for img in image_tags if img.get('src')]
product_data['Image URLs'] = ', '.join(image_urls)
# Extract available sizes
size_buttons = product_div.find_all('button', class_='quick-add-option')
sizes = [button.text.strip() for button in size_buttons if button.text.strip()]
product_data['Available Sizes'] = ', '.join(sizes)
# Extract color variants (if needed)
color_variants = []
color_divs = product_div.find_all('a', class_='gtm-color-change-trigger')
for color_div in color_divs:
color_name = color_div.get('data-gtm-product-name', '').strip()
color_code_div = color_div.find('div', class_='color-change-inner')
color_code = color_code_div['style'].split(':')[1].strip().rstrip(';') if color_code_div else None
color_variants.append(f"{color_name} ({color_code})")
product_data['Color Variants'] = '; '.join(color_variants)
except Exception as e:
print(f"Error extracting product info: {e}")
return product_data
def scrape_products(base_url):
"""
Scrapes all products from the given category URL.
"""
all_products = []
page_number = 1
while True:
url = f"{base_url}?page={page_number}"
print(f"Scraping page {page_number}: {url}")
soup = get_soup(url)
if not soup:
print("Failed to retrieve or parse page. Stopping scraper.")
break
# Find all product listings on the page
product_divs = soup.find_all('div', class_='cms-listing-col')
if not product_divs:
print("No products found on this page. Assuming end of listings.")
break
for product_div in product_divs:
product_info = extract_product_info(product_div)
all_products.append(product_info)
# Optional: Check if there's a next page
# This assumes the site uses pagination and there's a next button/link
pagination = soup.find('ul', class_='pagination')
if pagination:
next_button = pagination.find('a', {'aria-label': 'Next'})
if next_button and 'href' in next_button.attrs:
page_number += 1
# Polite scraping: wait for a random short duration
time.sleep(random.uniform(1, 3))
else:
break
else:
# If there's no pagination, assume all products are on a single page
break
return all_products
def save_to_csv(data, filename):
"""
Saves the extracted data to a CSV file.
"""
df = pd.DataFrame(data)
df.to_csv(filename, index=False, encoding='utf-8-sig')
print(f"Data saved to {filename}")
def main():
base_url = "https://www.armedangels.com/wo-en/women/tops/t-shirts"
products = scrape_products(base_url)
if products:
save_to_csv(products, "armedangels_tshirts.csv")
else:
print("No products were scraped.")
if __name__ == "__main__":
main()
Explanation of the Script
-
Headers Setup: The HEADERS dictionary is used to mimic a real browser. This can help bypass some basic anti-scraping mechanisms.
-
get_soup Function: Fetches the HTML content of a given URL and returns a BeautifulSoup object for parsing. It includes basic error handling to catch network-related issues.
-
extract_product_info Function: Takes a single product's HTML div and extracts relevant information:
- SKU: Retrieved from the
<meta> tag with itemprop="sku".
- Product Name & URL: Extracted from the
<a> tag with class product-info-link.
- Price: Extracted from the
<p> tag with class product-price.
- Image URLs: All image sources within the product are collected and joined as a comma-separated string.
- Available Sizes: Collected from buttons with the class
quick-add-option.
- Color Variants: Extracted from the
color-change-trigger links, capturing both the product name and the color code.
-
scrape_products Function: Handles the scraping process across multiple pages (pagination).
- Pagination Handling: Assumes that pagination is handled via query parameters (e.g.,
?page=2). It keeps incrementing the page number until no more products are found.
- Polite Scraping: Introduces random delays between requests to avoid overwhelming the server.
-
save_to_csv Function: Saves the collected product data into a CSV file named armedangels_tshirts.csv.
-
main Function: Orchestrates the scraping process by calling the necessary functions.
Running the Scraper
-
Save the Script: Save the above Python script to a file, e.g., armedangels_scraper.py.
-
Execute the Script:
python armedangels_scraper.py
-
Output: After running, you should find a armedangels_tshirts.csv file in the same directory containing the scraped product data.
Notes and Considerations
-
Dynamic Content: The provided HTML snippet suggests that the content is server-rendered. If you encounter pages where content is loaded dynamically via JavaScript (e.g., using AJAX), you might need to use Selenium or Playwright for scraping.
-
Respect Robots.txt and Terms of Service: Always check the website's robots.txt file and terms of service to ensure that you're allowed to scrape the content. Excessive scraping can lead to IP blocking or legal consequences.
-
Rate Limiting: The script includes random delays between requests to mimic human browsing behavior and reduce the risk of being blocked. Adjust the delay (time.sleep) as needed.
-
Error Handling: The script includes basic error handling. For production-level scrapers, consider implementing more robust logging and exception management.
-
Extending the Scraper: Depending on your needs, you can extend the scraper to handle other product categories, extract additional product attributes, or integrate with databases and APIs.
Sample Output
Here's how the CSV might look:
Note: The Image URLs and Color Variants fields may contain multiple entries separated by commas or semicolons.
Conclusion
This scraper provides a foundational framework to extract product data from the specified Armed Angels category page. Depending on the website's structure and any changes it might undergo, you may need to adjust the selectors or add additional logic. Always ensure that your scraping activities are compliant with the website's policies.