Okay, I've modified the previous script to prompt you for a Vinted search URL.
Crucial Points Before You Run:
- HTML Selectors are KEY: The most important and fragile part of this script is the
parse_listings function, specifically the lines that use soup.find_all(...) and card.find(...). Vinted's website structure (HTML tags and CSS class names) can change frequently. You will almost certainly need to adjust these selectors.
- How to Find Selectors:
- Open the Vinted search URL in your browser (Chrome, Firefox, Edge).
- Right-click on an item listing (e.g., on its title, price, or the whole card).
- Select "Inspect" or "Inspect Element."
- In the developer tools that open, examine the HTML. Look for the tags (like
<div>, <a>, <span>) and their class="..." or id="..." attributes that uniquely identify:
- The main container for each item.
- The item's title.
- The item's price.
- The link to the item's detail page.
- Update the selectors in the
parse_listings function accordingly. Vinted often uses dynamic class names (e.g., ItemBox_itemBox__a1B2c), so you might need to use partial matches with re.compile or look for more stable parent elements.
- Terms of Service: Remember Vinted's Terms of Service regarding automated access. Use responsibly and don't make requests too frequently.
- Dynamic Content: If Vinted loads listings heavily with JavaScript after the initial page load,
requests might not get all data. In that case, you'd need to switch to a more complex solution like Selenium (which controls a real browser). This script uses requests for simplicity.
import requests
from bs4 import BeautifulSoup
import time
import json
import re # For regular expressions (useful for dynamic class names and URL sanitization)
from urllib.parse import urlparse # For handling relative URLs
# --- Configuration ---
HEADERS = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
CHECK_INTERVAL_SECONDS = 300 # Check every 5 minutes (300 seconds)
# SEEN_ITEMS_FILE will be generated based on the URL
# Global variable to store the search URL for helper functions if needed
# This is used to construct absolute URLs for items if they are relative
USER_SEARCH_URL = ""
# --- Helper Functions ---
def generate_seen_items_filename(url):
"""Generates a filename based on the URL to keep seen items separate for different searches."""
sanitized_name = re.sub(r'[^a-zA-Z0-9_-]', '_', url)
# Truncate to avoid excessively long filenames
if len(sanitized_name) > 100:
sanitized_name = sanitized_name[:50] + "..." + sanitized_name[-47:]
return f"seen_items_{sanitized_name}.json"
def load_seen_items(filename):
try:
with open(filename, 'r') as f:
return set(json.load(f))
except FileNotFoundError:
print(f"No previous seen items file ('{filename}') found. Starting fresh.")
return set()
except json.JSONDecodeError:
print(f"Warning: Could not decode JSON from '{filename}'. File might be corrupted. Starting fresh.")
return set()
def save_seen_items(seen_items_set, filename):
try:
with open(filename, 'w') as f:
json.dump(list(seen_items_set), f, indent=2)
print(f"Saved {len(seen_items_set)} seen items to '{filename}'")
except Exception as e:
print(f"Error saving seen items to '{filename}': {e}")
def fetch_listings(search_url):
print(f"\nFetching listings from: {search_url}...")
try:
response = requests.get(search_url, headers=HEADERS, timeout=20) # Increased timeout
response.raise_for_status() # Raises an HTTPError for bad responses (4XX or 5XX)
return response.text
except requests.exceptions.Timeout:
print("Error: Request timed out.")
return None
except requests.exceptions.RequestException as e:
print(f"Error fetching page: {e}")
return None
def parse_listings(html_content, base_url_for_relative_paths):
if not html_content:
return []
soup = BeautifulSoup(html_content, 'html.parser')
listings = []
# !!! USER ACTION REQUIRED: UPDATE THESE SELECTORS !!!
# ----------------------------------------------------------------------------------
# These selectors are EXAMPLES and VERY LIKELY need to be changed based on
# Vinted's current HTML structure for your specific search results page.
#
# 1. Find the main container for each item listing:
# Common Vinted class (might change!): 'feed-grid__item' or something with 'ItemBox'
# Using re.compile for partial match on dynamic class names:
item_containers = soup.find_all('div', class_=re.compile(r'ItemBox_itemBox', re.IGNORECASE))
# If the above doesn't work, try a more generic approach or inspect the HTML carefully.
# Example: item_containers = soup.select('div.feed-grid__item article.feed-grid__item--card')
if not item_containers:
print("\nCRITICAL: No item containers found using the current selectors.")
print("Please inspect the Vinted page's HTML and update the 'item_containers' selector in the `parse_listings` function.")
# print("First 1000 characters of HTML received (for debugging selectors):")
# print(html_content[:1000]) # Uncomment this to see the HTML if you're stuck
return []
print(f"Found {len(item_containers)} potential item cards. Parsing details...")
for index, card in enumerate(item_containers):
title = "N/A"
price = "N/A"
link_href = None
item_id_from_link = None
# 2. Find the link (<a> tag) to the item, which often contains the title or has it nearby.
# The link is usually the most reliable way to get a unique ID.
# Vinted item links often look like /items/1234567-item-name
link_tag = card.find('a', href=re.compile(r'/items/\d+')) # Looks for links like /items/12345-....
# Alternative: link_tag = card.find('a', class_=re.compile(r'ItemBox_link'))
if link_tag and link_tag.has_attr('href'):
link_href = link_tag['href']
# Construct absolute URL if it's relative
if link_href.startswith('/'):
link_href = base_url_for_relative_paths + link_href
item_id_from_link = link_href # The full URL is a good unique ID
# 3. Find the item title.
# Sometimes it's the text of the link_tag, an alt attribute of an image,
# or a specific heading (h2, h3) or div with a title-like class.
# Try aria-label on the link first, as Vinted sometimes uses this.
if link_tag.get('aria-label'):
title = link_tag['aria-label'].strip()
elif link_tag.find(['h2','h3','div'], class_=re.compile(r'title', re.I)):
title = link_tag.find(['h2','h3','div'], class_=re.compile(r'title', re.I)).get_text(strip=True)
else:
# Fallback: try to get any descriptive text from within the link
title_texts = link_tag.find_all(string=True, recursive=True)
cleaned_title_texts = [t.strip() for t in title_texts if t.strip() and len(t.strip()) > 3] # Avoid empty/short strings
if cleaned_title_texts:
title = ' - '.join(cleaned_title_texts) # Join multiple text parts if found
else:
title = "Title not found"
# 4. Find the item price.
# Price elements often have classes like 'price', 'amount', or currency symbols.
price_element = card.find(['span', 'div'], class_=re.compile(r'price|currency|amount', re.IGNORECASE))
if price_element:
price = price_element.get_text(strip=True)
else:
# Try finding text with currency symbols as a fallback
price_text_nodes = card.find_all(string=re.compile(r'[€$£¥]')) # Add more currency symbols if needed
if price_text_nodes:
price = price_text_nodes[0].strip() # Take the first one found
else: # If a suitable link_tag is not found in this card
# print(f" Skipping card {index+1}: Could not find a valid item link.")
continue # Skip this card if no primary link is found
if item_id_from_link: # Ensure we have a unique ID
listings.append({
'id': item_id_from_link, # Use the full absolute link as a unique ID
'title': title,
'price': price,
'link': item_id_from_link
})
# else:
# print(f" Skipping card {index+1}: Could not extract required info (ID). Title: {title}, Price: {price}")
pass
return listings
# --- Main Logic ---
if __name__ == "__main__":
print("--- Vinted New Listing Notifier ---")
print("Disclaimer: Use responsibly and be mindful of Vinted's Terms of Service.")
print("\nIMPORTANT: This script's success heavily depends on correct HTML selectors.")
print("If it doesn't find items, or finds incorrect data, you MUST update the selectors")
print("in the `parse_listings` function by inspecting Vinted's HTML in your browser.")
print("-" * 40)
while True:
USER_SEARCH_URL = input("Paste the FULL Vinted search URL (e.g., from your browser after searching and sorting by 'Newest') and press Enter:\n(Type 'exit' to quit)\n> ").strip()
if USER_SEARCH_URL.lower() == 'exit':
print("Exiting.")
exit()
if not (USER_SEARCH_URL.startswith("http://") or USER_SEARCH_URL.startswith("https://")):
print("Invalid URL. Please make sure it starts with http:// or https://")
else:
break # Valid URL entered
parsed_uri = urlparse(USER_SEARCH_URL)
BASE_VINTED_URL = f"{parsed_uri.scheme}://{parsed_uri.netloc}"
SEEN_ITEMS_FILE = generate_seen_items_filename(USER_SEARCH_URL)
seen_items_ids = load_seen_items(SEEN_ITEMS_FILE)
print(f"\nMonitoring URL: {USER_SEARCH_URL}")
print(f"Tracking seen items in: {SEEN_ITEMS_FILE}")
print(f"Loaded {len(seen_items_ids)} previously seen item IDs.")
print(f"Base URL for relative links: {BASE_VINTED_URL}")
print("-" * 40)
try:
while True:
html_page_content = fetch_listings(USER_SEARCH_URL)
new_items_found_this_run = 0
if html_page_content:
current_listings_on_page = parse_listings(html_page_content, BASE_VINTED_URL)
if not current_listings_on_page and not seen_items_ids:
# Only print strong warning if it's the first fetch and nothing is found
print("\nWARNING: No listings were parsed from the page on the first attempt.")
print("This strongly suggests the HTML selectors in `parse_listings` are incorrect for this URL or Vinted's page structure.")
print("Please review the selectors. The script will continue trying, but may not find items until selectors are fixed.")
for item in reversed(current_listings_on_page): # Process older items first from the page
if item['id'] not in seen_items_ids:
print("=" * 20)
print(f"🎉 NEW ITEM FOUND! 🎉 ({time.strftime('%Y-%m-%d %H:%M:%S')})")
print(f" Title: {item['title']}")
print(f" Price: {item['price']}")
print(f" Link: {item['link']}")
print("=" * 20)
seen_items_ids.add(item['id'])
new_items_found_this_run += 1
# ---- TODO: Add your notification logic here ----
# Example: send_telegram_notification(item['title'], item['link'])
# Example: send_email_alert(item)
# -------------------------------------------------
if new_items_found_this_run > 0:
print(f"Added {new_items_found_this_run} new item(s) to seen list.")
save_seen_items(seen_items_ids, SEEN_ITEMS_FILE)
else:
if current_listings_on_page: # Parsed some items, but they were all old
print(f"No new items found this cycle (Total seen: {len(seen_items_ids)}, Parsed this cycle: {len(current_listings_on_page)}).")
# If current_listings_on_page is empty, the warning from above (or a softer one) would have been printed.
else: # fetch_listings returned None (error during fetch)
print("Failed to fetch page content in this cycle. Will retry.")
print(f"--- Waiting for {CHECK_INTERVAL_SECONDS // 60} minutes and {CHECK_INTERVAL_SECONDS % 60} seconds before next check (Current time: {time.strftime('%H:%M:%S')}) ---")
time.sleep(CHECK_INTERVAL_SECONDS)
except KeyboardInterrupt:
print("\nScript interrupted by user.")
finally:
if seen_items_ids: # Check if there's anything to save
print("Saving seen items before exiting...")
save_seen_items(seen_items_ids, SEEN_ITEMS_FILE)
print("Exiting script.")