Guías prácticasRastrea cualquier sitio web
Crea un script de vigilancia de precios
Rastrea una página de producto y extrae su precio.
Rastrea una página de producto y extrae el precio con un selector CSS o un patrón. Sustituye la URL y el selector por los de la página que vigilas.
import os
import requests
from bs4 import BeautifulSoup
API_KEY = os.environ["PILOTERR_API_KEY"]
WATCH_URL = "https://www.example-shop.com/product/123"
def crawl(url: str) -> str:
r = requests.get("https://api.piloterr.com/v2/website/crawler",
headers={"x-api-key": API_KEY}, params={"query": url})
if r.status_code != 200:
raise RuntimeError(f"Error {r.status_code}: {r.text}")
return r.json()
def extract_price(html: str) -> str | None:
soup = BeautifulSoup(html, "html.parser")
el = soup.select_one("[data-price], .price, #price")
return el.get_text(strip=True) if el else None
price = extract_price(crawl(WATCH_URL))
print(f"Current price: {price}" if price else "Price element not found.")