Looking at your code and the problem you're facing, the issue with the "Save Up To" field being blank is likely due to one of these scenarios:
- The
.p-price__savings element is loaded dynamically after the initial page render
- The selector might be incorrect or the element structure has changed
- The savings information might be loaded via JavaScript after user interaction
Here's an enhanced version of your code with several strategies to fix the "Save Up To" extraction:
import asyncio
import pandas as pd
import xlsxwriter
import requests
from io import BytesIO
from PIL import Image
import os
from playwright.async_api import async_playwright
PUBLIX_URL = "https://www.publix.com/savings/weekly-ad/bogo"
OUTPUT_DIR = "output"
os.makedirs(OUTPUT_DIR, exist_ok=True)
def download_image(url, idx):
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
img = Image.open(BytesIO(response.content))
img_path = os.path.join(OUTPUT_DIR, f"temp_img_{idx}.png")
img.save(img_path)
return img_path
except:
return None
def save_to_excel(items):
filename = os.path.join(OUTPUT_DIR, "publix_bogo_deals.xlsx")
workbook = xlsxwriter.Workbook(filename)
worksheet = workbook.add_worksheet()
headers = ["Title", "Badge", "Description", "Save Up To", "Valid Dates"]
for col, header in enumerate(headers):
worksheet.write(0, col, header)
worksheet.set_column("A:E", 35)
worksheet.set_column("F:F", 20)
for idx, item in enumerate(items):
row = idx + 1
worksheet.write(row, 0, item.get("title"))
worksheet.write(row, 1, item.get("badge"))
worksheet.write(row, 2, item.get("description"))
worksheet.write(row, 3, item.get("save_up_to"))
worksheet.write(row, 4, item.get("valid"))
img_path = download_image(item.get("img"), idx)
if img_path:
worksheet.set_row(row, 100)
worksheet.insert_image(row, 5, img_path, {"x_scale": 0.5, "y_scale": 0.5})
workbook.close()
print(f"Excel file saved to: {filename}")
async def run_scraper():
async with async_playwright() as p:
browser = await p.chromium.launch(headless=False)
context = await browser.new_context()
page = await context.new_page()
# Enable console logging to debug
page.on("console", lambda msg: print(f"Browser console: {msg.text}"))
await page.goto(PUBLIX_URL)
await page.wait_for_timeout(8000)
# Scroll to load all items
for _ in range(10):
await page.mouse.wheel(0, 1500)
await page.wait_for_timeout(1500) # Increased wait time
await page.wait_for_selector('.p-card', timeout=8000)
await page.wait_for_timeout(5000) # Extra wait for dynamic content
# Enhanced extraction script with multiple selector strategies
extraction_script = """
() => {
const cards = Array.from(document.querySelectorAll('.p-card'));
console.log(`Found ${cards.length} cards`);
return cards.map((card, index) => {
// Debug: log what we find for each card
const priceElements = card.querySelectorAll('[class*="price"], [class*="saving"], [class*="Price"], [class*="Saving"]');
console.log(`Card ${index}: Found ${priceElements.length} price-related elements`);
// Try multiple strategies to find savings
let saveUpTo = '';
// Strategy 1: Direct selector
const savingsElement = card.querySelector('.p-price__savings');
if (savingsElement) {
saveUpTo = savingsElement.innerText || savingsElement.textContent || '';
}
// Strategy 2: Look for text containing "Save"
if (!saveUpTo) {
const allTexts = card.querySelectorAll('*');
for (let elem of allTexts) {
const text = elem.innerText || elem.textContent || '';
if (text.includes('Save') && text.includes('$')) {
saveUpTo = text.trim();
break;
}
}
}
// Strategy 3: Check for price-related classes
if (!saveUpTo) {
const priceClasses = ['p-price', 'price', 'savings', 'discount'];
for (let className of priceClasses) {
const elem = card.querySelector(`[class*="${className}"]`);
if (elem && elem.innerText && elem.innerText.includes('$')) {
saveUpTo = elem.innerText;
break;
}
}
}
return {
title: card.querySelector('.title-wrapper')?.innerText || '',
img: card.querySelector('img')?.src || '',
badge: card.querySelector('.p-savings-badge__text')?.innerText || '',
description: card.querySelector('.p-savings-badge__description')?.innerText || '',
save_up_to: saveUpTo,
valid: card.querySelector('.valid-dates')?.innerText || ''
};
});
}
"""
items = await page.evaluate(extraction_script)
print(f"Extracted {len(items)} items.")
# Print sample data for debugging
if items:
print("\nSample item data:")
for key, value in items[0].items():
print(f" {key}: {value}")
# Alternative: Try hovering over cards to trigger lazy loading
if not any(item.get("save_up_to") for item in items):
print("\nTrying hover strategy...")
cards = await page.query_selector_all('.p-card')
for i, card in enumerate(cards[:5]): # Test on first 5 cards
await card.hover()
await page.wait_for_timeout(500)
# Re-extract after hovering
items = await page.evaluate(extraction_script)
save_to_excel(items)
await browser.close()
async def debug_page_structure():
"""Debug function to understand the page structure"""
async with async_playwright() as p:
browser = await p.chromium.launch(headless=False)
page = await browser.new_page()
await page.goto(PUBLIX_URL)
await page.wait_for_timeout(8000)
# Get all class names containing 'price' or 'saving'
debug_script = """
() => {
const allElements = document.querySelectorAll('*');
const priceClasses = new Set();
allElements.forEach(elem => {
const classes = elem.className.split(' ');
classes.forEach(cls => {
if (cls && (cls.toLowerCase().includes('price') ||
cls.toLowerCase().includes('saving') ||
cls.toLowerCase().includes('discount'))) {
priceClasses.add(cls);
}
});
});
return Array.from(priceClasses);
}
"""
price_classes = await page.evaluate(debug_script)
print("Found price-related classes:", price_classes)
# Check first card structure
first_card_structure = await page.evaluate("""
() => {
const card = document.querySelector('.p-card');
if (!card) return 'No card found';
const structure = [];
const walker = document.createTreeWalker(
card,
NodeFilter.SHOW_ELEMENT,
null,
false
);
let node;
while (node = walker.nextNode()) {
if (node.className && typeof node.className === 'string') {
structure.push({
tag: node.tagName,
class: node.className,
text: node.innerText?.substring(0, 50)
});
}
}
return structure;
}
""")
print("\nFirst card structure:")
for elem in first_card_structure[:20]: # Show first 20 elements
print(f" {elem}")
await browser.close()
if __name__ == "__main__":
# Run the main scraper
asyncio.run(run_scraper())
# Uncomment to debug page structure
# asyncio.run(debug_page_structure())