Skip to content

Instantly share code, notes, and snippets.

@phoenixthrush
Last active January 6, 2026 22:55
Show Gist options
  • Select an option

  • Save phoenixthrush/096209cb679863cff26e5b6b5f35ff80 to your computer and use it in GitHub Desktop.

Select an option

Save phoenixthrush/096209cb679863cff26e5b6b5f35ff80 to your computer and use it in GitHub Desktop.
Backmarket Price Watcher in Python with Discord Webhook Notifications #Python #Scraper #Discord #BackMarket
"""
Copyright (c) 2026 phoenixthrush
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
"""
import json
import os
import re
import time
from dotenv import load_dotenv, set_key
import niquests
URL = "https://www.backmarket.de/de-de/p/iphone-15-pro"
HEADERS = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Sec-Fetch-Site": "none",
"Sec-Fetch-Mode": "navigate",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 "
"(KHTML, like Gecko) Version/26.2 Safari/605.1.15",
"Accept-Language": "en-US,en;q=0.9",
"Sec-Fetch-Dest": "document",
"Priority": "u=0, i",
}
SCRIPT_PATTERN = re.compile(
r'<script\s+type="application/json"\s+data-nuxt-data="nuxt-app"'
r'\s+data-ssr="true"\s+id="__NUXT_DATA__">\s*(.*?)\s*</script>',
re.DOTALL,
)
def load_or_save_webhook():
"""Load WEBHOOK_URL from .env or ask user and persist it."""
load_dotenv()
webhook = os.getenv("WEBHOOK_URL")
if not webhook:
webhook = input("Enter your Discord webhook URL: ").strip()
if not webhook.startswith("https://discord.com/api/webhooks/"):
raise ValueError("Invalid Discord webhook URL.")
set_key(".env", "WEBHOOK_URL", webhook)
os.environ["WEBHOOK_URL"] = webhook
print("Webhook saved to .env")
return webhook
def fetch_page(url, headers, max_retries=3, delay=1):
"""
Fetch page content with headers, retrying up to max_retries times
if access is blocked by Cloudflare.
"""
for attempt in range(1, max_retries + 1):
try:
response = niquests.get(url, headers=headers)
if "Enable JavaScript and cookies to continue" in response.text:
raise RuntimeError("Access blocked by Cloudflare.")
return response.text
except Exception as e:
if attempt < max_retries:
print(f"Attempt {attempt} failed: {e}. Retrying in {delay}s...")
time.sleep(delay)
else:
raise RuntimeError(f"Failed after {max_retries} attempts: {e}")
def extract_nuxt_json(html_text):
"""Extract JSON from the Nuxt <script> tag."""
match = SCRIPT_PATTERN.search(html_text)
if not match:
raise ValueError("No matching <script> tag found.")
return json.loads(match.group(1))
def save_json(data, filename="data.json"):
"""Save JSON data to a file in pretty format."""
with open(filename, "w", encoding="utf-8") as f:
json.dump(data, f, indent=4, ensure_ascii=False)
print("JSON data saved to data.json.")
def extract_price(data, grade_label="Hervorragend"):
"""
Extract the price of a product with a specific grade label.
Returns None if not found.
"""
try:
# Find the index where the grade label matches
for i, item in enumerate(data):
if item == grade_label:
# Look for price in the next few positions (within 5 positions)
# Check for price patterns: decimal strings or price objects
for j in range(1, 6):
if i + j >= len(data):
break
candidate = data[i + j]
# If it's a string that looks like a price (e.g., "583.00")
if isinstance(candidate, str) and candidate.replace('.', '').isdigit():
return candidate
# If it's a price object, skip it and continue looking
if isinstance(candidate, dict) and 'amount' in candidate and 'currency' in candidate:
continue
# Skip other non-price items
continue
except (KeyError, TypeError, IndexError):
return None
return None
def main():
try:
print(URL)
html_text = fetch_page(URL, HEADERS)
nuxt_data = extract_nuxt_json(html_text)
# save_json(nuxt_data)
price = extract_price(nuxt_data, grade_label="Hervorragend")
if price is not None:
print(f"Price for 'Hervorragend': {price} €")
niquests.post(
load_or_save_webhook(),
json={
"content": f"{'@everyone\n\n' if float(price) < 550 else ''}🚨 iPhone 15 Pro 'Hervorragend' available for {price} €! 🚨\n{URL}"
},
)
else:
print("Price for 'Hervorragend' not found.")
except Exception as e:
print(f"Error: {e}")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment