Update scraper.py
Browse files- scraper.py +74 -140
scraper.py
CHANGED
|
@@ -7,19 +7,21 @@ from datetime import datetime
|
|
| 7 |
from fake_useragent import UserAgent
|
| 8 |
import random
|
| 9 |
|
| 10 |
-
# Configuration
|
| 11 |
-
|
| 12 |
-
|
|
|
|
|
|
|
| 13 |
ua = UserAgent()
|
| 14 |
|
| 15 |
def get_authenticated_session():
|
| 16 |
-
"""Create a session
|
| 17 |
session = requests.Session()
|
| 18 |
|
| 19 |
headers = {
|
| 20 |
'User-Agent': ua.random,
|
| 21 |
'Accept-Language': 'en-CA,en-US;q=0.9,en;q=0.8',
|
| 22 |
-
'Accept': '
|
| 23 |
'Referer': 'https://www.walmart.ca/en',
|
| 24 |
'X-Requested-With': 'XMLHttpRequest',
|
| 25 |
'DNT': '1'
|
|
@@ -27,191 +29,123 @@ def get_authenticated_session():
|
|
| 27 |
|
| 28 |
session.headers.update(headers)
|
| 29 |
|
| 30 |
-
# Set
|
| 31 |
session.cookies.update({
|
| 32 |
'bm_sv': f"{random.randint(1000000000000,9999999999999)}",
|
| 33 |
'ak_bmsc': f"F{random.randint(100000,999999)}~1",
|
| 34 |
'storeSelected': 'true',
|
| 35 |
-
'
|
|
|
|
| 36 |
})
|
| 37 |
|
| 38 |
return session
|
| 39 |
|
| 40 |
-
def
|
| 41 |
-
"""
|
| 42 |
-
if not address_dict:
|
| 43 |
-
return None
|
| 44 |
-
|
| 45 |
-
parts = [
|
| 46 |
-
address_dict.get('street'),
|
| 47 |
-
address_dict.get('city'),
|
| 48 |
-
address_dict.get('province'),
|
| 49 |
-
address_dict.get('postalCode')
|
| 50 |
-
]
|
| 51 |
-
return ', '.join(filter(None, parts))
|
| 52 |
-
|
| 53 |
-
def extract_field(soup, selectors):
|
| 54 |
-
"""Generic field extractor with multiple selectors"""
|
| 55 |
-
for tag, attrs in selectors:
|
| 56 |
-
element = soup.find(tag, attrs)
|
| 57 |
-
if element:
|
| 58 |
-
text = element.get_text(strip=True)
|
| 59 |
-
if text:
|
| 60 |
-
return text
|
| 61 |
-
return None
|
| 62 |
-
|
| 63 |
-
def extract_price(soup):
|
| 64 |
-
"""Specialized price extractor"""
|
| 65 |
-
price_selectors = [
|
| 66 |
-
('span', {'itemprop': 'price'}),
|
| 67 |
-
('div', {'data-automation': 'price-amount'}),
|
| 68 |
-
('span', {'class': 'price-characteristic'}),
|
| 69 |
-
('span', {'data-automation': 'current-price'})
|
| 70 |
-
]
|
| 71 |
-
|
| 72 |
-
price = extract_field(soup, price_selectors)
|
| 73 |
-
if price:
|
| 74 |
-
cleaned = re.sub(r'[^\d.,]', '', price)
|
| 75 |
-
if '.' in cleaned:
|
| 76 |
-
return f"{float(cleaned):.2f}"
|
| 77 |
-
return cleaned
|
| 78 |
-
return None
|
| 79 |
-
|
| 80 |
-
def extract_quantity(soup):
|
| 81 |
-
"""Extract product quantity/package size"""
|
| 82 |
-
# Try from product name first
|
| 83 |
-
name = extract_field(soup, [('h1', {'itemprop': 'name'})])
|
| 84 |
-
if name:
|
| 85 |
-
quantity = detect_quantity_in_text(name)
|
| 86 |
-
if quantity:
|
| 87 |
-
return quantity
|
| 88 |
-
|
| 89 |
-
# Try specific quantity elements
|
| 90 |
-
quantity_selectors = [
|
| 91 |
-
('span', {'data-automation': 'product-quantity'}),
|
| 92 |
-
('div', {'class': 'package-size'})
|
| 93 |
-
]
|
| 94 |
-
|
| 95 |
-
return extract_field(soup, quantity_selectors)
|
| 96 |
-
|
| 97 |
-
def detect_quantity_in_text(text):
|
| 98 |
-
"""Helper to find quantity patterns in text"""
|
| 99 |
-
patterns = [
|
| 100 |
-
r'(\d+\s*(g|kg|ml|l|oz|lb|pack|ct|count|ea)\b)',
|
| 101 |
-
r'(\d+\s*[-x]\s*\d+\s*(g|kg|ml|l|oz|lb)\b)'
|
| 102 |
-
]
|
| 103 |
-
|
| 104 |
-
for pattern in patterns:
|
| 105 |
-
match = re.search(pattern, text, re.IGNORECASE)
|
| 106 |
-
if match:
|
| 107 |
-
return match.group(1)
|
| 108 |
-
return None
|
| 109 |
-
|
| 110 |
-
def get_store_specific_price(session, url, postal_code=DEFAULT_POSTAL_CODE):
|
| 111 |
-
"""Get in-store pricing for Atlantic Canada locations"""
|
| 112 |
try:
|
| 113 |
-
#
|
| 114 |
-
|
| 115 |
-
if len(clean_postal) != 6:
|
| 116 |
-
clean_postal = "B1P7H9" # Fallback to Sydney, NS
|
| 117 |
-
|
| 118 |
-
# Extract product ID
|
| 119 |
-
product_id = re.search(r'/ip/([^/?]+)', url)
|
| 120 |
if not product_id:
|
| 121 |
return None
|
| 122 |
|
| 123 |
api_url = "https://www.walmart.ca/api/product-page/find-in-store"
|
| 124 |
|
| 125 |
params = {
|
| 126 |
-
'lat': str(
|
| 127 |
-
'lng': str(
|
| 128 |
'locale': 'en',
|
| 129 |
-
'postalCode':
|
| 130 |
-
'upc': product_id.group(1)
|
|
|
|
| 131 |
}
|
| 132 |
|
| 133 |
-
|
|
|
|
| 134 |
|
| 135 |
response = session.get(
|
| 136 |
api_url,
|
| 137 |
params=params,
|
| 138 |
-
headers={
|
| 139 |
-
'Accept': 'application/json',
|
| 140 |
-
'Referer': url
|
| 141 |
-
},
|
| 142 |
timeout=20
|
| 143 |
)
|
| 144 |
|
| 145 |
data = response.json()
|
| 146 |
|
| 147 |
if data.get('info'):
|
| 148 |
-
store_info = data['info']
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
|
|
|
| 157 |
return None
|
| 158 |
|
| 159 |
except Exception as e:
|
| 160 |
-
print(f"
|
| 161 |
return None
|
| 162 |
|
| 163 |
-
def scrape_walmart_product(
|
| 164 |
-
"""Main
|
| 165 |
try:
|
| 166 |
session = get_authenticated_session()
|
| 167 |
|
| 168 |
-
# Initial request to
|
| 169 |
-
time.sleep(
|
| 170 |
-
session.get("https://www.walmart.ca/en", timeout=10)
|
| 171 |
|
| 172 |
-
#
|
| 173 |
-
time.sleep(
|
| 174 |
-
response = session.get(
|
| 175 |
|
| 176 |
-
# Check
|
| 177 |
if "verify-your-identity" in response.url.lower():
|
| 178 |
-
raise Exception("
|
| 179 |
|
| 180 |
soup = BeautifulSoup(response.text, 'html.parser')
|
| 181 |
|
|
|
|
| 182 |
product_data = {
|
| 183 |
-
'product_name':
|
| 184 |
-
('h1', {'itemprop': 'name'}),
|
| 185 |
-
('h1', {'data-automation': 'product-title'})
|
| 186 |
-
]),
|
| 187 |
'online_price': extract_price(soup),
|
| 188 |
-
'original_price': extract_field(soup, [
|
| 189 |
-
('span', {'class': 'strike-through'})
|
| 190 |
-
]),
|
| 191 |
'quantity': extract_quantity(soup),
|
| 192 |
-
'
|
| 193 |
-
|
| 194 |
-
]) or "Available",
|
| 195 |
-
'url': url,
|
| 196 |
-
'region': 'Nova Scotia',
|
| 197 |
-
'default_postal_code': DEFAULT_POSTAL_CODE
|
| 198 |
}
|
| 199 |
|
| 200 |
-
# Get
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
|
| 210 |
return product_data
|
| 211 |
|
| 212 |
except Exception as e:
|
| 213 |
return {
|
| 214 |
'error': str(e),
|
| 215 |
-
'solution': 'Try again with different network or wait
|
| 216 |
-
'
|
| 217 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
from fake_useragent import UserAgent
|
| 8 |
import random
|
| 9 |
|
| 10 |
+
# Sydney, Nova Scotia Configuration
|
| 11 |
+
SYDNEY_POSTAL = "B1P 7H9"
|
| 12 |
+
SYDNEY_COORDS = (46.1368, -60.1942) # Walmart Sydney NS coordinates
|
| 13 |
+
STORE_ID = "3108" # Walmart Sydney store ID
|
| 14 |
+
|
| 15 |
ua = UserAgent()
|
| 16 |
|
| 17 |
def get_authenticated_session():
|
| 18 |
+
"""Create a session with Nova Scotia store preferences"""
|
| 19 |
session = requests.Session()
|
| 20 |
|
| 21 |
headers = {
|
| 22 |
'User-Agent': ua.random,
|
| 23 |
'Accept-Language': 'en-CA,en-US;q=0.9,en;q=0.8',
|
| 24 |
+
'Accept': 'application/json',
|
| 25 |
'Referer': 'https://www.walmart.ca/en',
|
| 26 |
'X-Requested-With': 'XMLHttpRequest',
|
| 27 |
'DNT': '1'
|
|
|
|
| 29 |
|
| 30 |
session.headers.update(headers)
|
| 31 |
|
| 32 |
+
# Set cookies to target Sydney NS store specifically
|
| 33 |
session.cookies.update({
|
| 34 |
'bm_sv': f"{random.randint(1000000000000,9999999999999)}",
|
| 35 |
'ak_bmsc': f"F{random.randint(100000,999999)}~1",
|
| 36 |
'storeSelected': 'true',
|
| 37 |
+
'preferredStore': STORE_ID, # Sydney Walmart store ID
|
| 38 |
+
'regionSelected': 'NS'
|
| 39 |
})
|
| 40 |
|
| 41 |
return session
|
| 42 |
|
| 43 |
+
def get_sydney_store_price(session, product_url):
|
| 44 |
+
"""Get pricing specifically for Sydney NS Walmart store"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
try:
|
| 46 |
+
# Extract product ID from URL
|
| 47 |
+
product_id = re.search(r'/ip/([^/?]+)', product_url)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
if not product_id:
|
| 49 |
return None
|
| 50 |
|
| 51 |
api_url = "https://www.walmart.ca/api/product-page/find-in-store"
|
| 52 |
|
| 53 |
params = {
|
| 54 |
+
'lat': str(SYDNEY_COORDS[0]),
|
| 55 |
+
'lng': str(SYDNEY_COORDS[1]),
|
| 56 |
'locale': 'en',
|
| 57 |
+
'postalCode': SYDNEY_POSTAL[:3] + " " + SYDNEY_POSTAL[3:6],
|
| 58 |
+
'upc': product_id.group(1),
|
| 59 |
+
'storeId': STORE_ID # Explicitly specify Sydney store
|
| 60 |
}
|
| 61 |
|
| 62 |
+
# Add random delay to mimic human behavior
|
| 63 |
+
time.sleep(random.uniform(2.0, 4.0))
|
| 64 |
|
| 65 |
response = session.get(
|
| 66 |
api_url,
|
| 67 |
params=params,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
timeout=20
|
| 69 |
)
|
| 70 |
|
| 71 |
data = response.json()
|
| 72 |
|
| 73 |
if data.get('info'):
|
| 74 |
+
store_info = next((item for item in data['info'] if item.get('id') == STORE_ID), None)
|
| 75 |
+
if store_info:
|
| 76 |
+
return {
|
| 77 |
+
'store_price': store_info.get('sellPrice'),
|
| 78 |
+
'store_original_price': store_info.get('price'),
|
| 79 |
+
'store_availability': store_info.get('availabilityStatus'),
|
| 80 |
+
'confirmed_location': 'Walmart Sydney, NS',
|
| 81 |
+
'store_address': '750 Kings Road, Sydney, NS B1P 7H9',
|
| 82 |
+
'last_checked': datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 83 |
+
}
|
| 84 |
return None
|
| 85 |
|
| 86 |
except Exception as e:
|
| 87 |
+
print(f"Error getting Sydney store price: {str(e)}")
|
| 88 |
return None
|
| 89 |
|
| 90 |
+
def scrape_walmart_product(product_url):
|
| 91 |
+
"""Main function optimized for Sydney NS Walmart"""
|
| 92 |
try:
|
| 93 |
session = get_authenticated_session()
|
| 94 |
|
| 95 |
+
# Initial request to set location cookies
|
| 96 |
+
time.sleep(1.5)
|
| 97 |
+
session.get(f"https://www.walmart.ca/en/store/{STORE_ID}", timeout=10)
|
| 98 |
|
| 99 |
+
# Get product page
|
| 100 |
+
time.sleep(2.0)
|
| 101 |
+
response = session.get(product_url, timeout=15)
|
| 102 |
|
| 103 |
+
# Check if we got the product page
|
| 104 |
if "verify-your-identity" in response.url.lower():
|
| 105 |
+
raise Exception("CAPTCHA triggered - try again later")
|
| 106 |
|
| 107 |
soup = BeautifulSoup(response.text, 'html.parser')
|
| 108 |
|
| 109 |
+
# Extract base product info
|
| 110 |
product_data = {
|
| 111 |
+
'product_name': soup.find('h1', {'itemprop': 'name'}).get_text(strip=True) if soup.find('h1', {'itemprop': 'name'}) else None,
|
|
|
|
|
|
|
|
|
|
| 112 |
'online_price': extract_price(soup),
|
|
|
|
|
|
|
|
|
|
| 113 |
'quantity': extract_quantity(soup),
|
| 114 |
+
'url': product_url,
|
| 115 |
+
'target_store': 'Sydney, NS (Store #3108)'
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
}
|
| 117 |
|
| 118 |
+
# Get Sydney-specific pricing
|
| 119 |
+
sydney_price = get_sydney_store_price(session, product_url)
|
| 120 |
+
if sydney_price:
|
| 121 |
+
product_data.update({
|
| 122 |
+
'in_store_price': sydney_price['store_price'],
|
| 123 |
+
'price_difference': calculate_price_difference(product_data['online_price'], sydney_price['store_price']),
|
| 124 |
+
'store_availability': sydney_price['store_availability'],
|
| 125 |
+
'confirmed_location': sydney_price['confirmed_location']
|
| 126 |
+
})
|
| 127 |
|
| 128 |
return product_data
|
| 129 |
|
| 130 |
except Exception as e:
|
| 131 |
return {
|
| 132 |
'error': str(e),
|
| 133 |
+
'solution': 'Try again with different network or wait 15 minutes',
|
| 134 |
+
'store_info': 'Targeting Walmart Sydney NS (750 Kings Road)'
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
def calculate_price_difference(online_price, store_price):
|
| 138 |
+
"""Calculate the price difference between online and Sydney store"""
|
| 139 |
+
try:
|
| 140 |
+
online = float(online_price) if online_price else 0
|
| 141 |
+
store = float(store_price) if store_price else 0
|
| 142 |
+
difference = store - online
|
| 143 |
+
if difference > 0:
|
| 144 |
+
return f"${difference:.2f} more expensive in Sydney store"
|
| 145 |
+
elif difference < 0:
|
| 146 |
+
return f"${abs(difference):.2f} cheaper in Sydney store"
|
| 147 |
+
return "Same price online and in-store"
|
| 148 |
+
except:
|
| 149 |
+
return "Price comparison unavailable"
|
| 150 |
+
|
| 151 |
+
# [Keep the existing extract_price() and extract_quantity() functions from previous version]
|