Web Scraping & Bots · Lección

Limitación de velocidad y rastreo respetuoso

Aprenda a regular las solicitudes, respetar crawl-delay y evitar sobrecargar los servidores para que su scraping sea ético y sostenible.

Lección 4 de 413 pasos

Limitación de velocidad y rastreo respetuoso es una lección gratuita de Web Scraping & Bots en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Web Scraping & Bots, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Web Scraping & Bots incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

Why Rate Limiting Matters

Even when scraping is legally permitted, hammering a server with rapid requests can degrade the site for real users and get your IP banned.

Respectful crawling means pacing your requests so you gather data without harming the host.

The Cost of a Request

Every request consumes server CPU, bandwidth, and database load. A scraper firing hundreds of requests per second behaves like a denial-of-service attack, even unintentionally.

  • Small sites have limited capacity.
  • Bursts spike server load.
  • Steady, slow traffic is far kinder.

Reading Crawl-Delay

Many robots.txt files include a Crawl-delay directive specifying seconds to wait between requests. Honor it as a baseline minimum.

User-agent: *
Crawl-delay: 10
Disallow: /private/

A Simple Delay

The most basic throttle adds a pause between requests. A fixed delay is fine for low-volume jobs.

import time
import requests

for url in urls:
    requests.get(url)
    time.sleep(2)  # at least 2 seconds between requests

Randomized Delays

Fixed intervals create a robotic, easily-detected pattern. Adding jitter makes traffic look more human and spreads load.

import random, time

delay = random.uniform(1.5, 4.0)
time.sleep(delay)

Token Bucket Throttling

For steadier control, a token bucket permits a fixed average rate while allowing small bursts. Tokens refill over time; each request spends one.

import time

class RateLimiter:
    def __init__(self, rate):
        self.rate = rate
        self.last = time.time()
    def wait(self):
        now = time.time()
        gap = 1.0 / self.rate
        sleep = gap - (now - self.last)
        if sleep > 0:
            time.sleep(sleep)
        self.last = time.time()

Respecting HTTP 429

A 429 Too Many Requests response is the server telling you to slow down. Check for a Retry-After header and back off for that duration.

resp = requests.get(url)
if resp.status_code == 429:
    wait = int(resp.headers.get('Retry-After', 30))
    time.sleep(wait)

Exponential Backoff

On repeated errors, increase the wait exponentially rather than retrying immediately. This relieves a struggling server and improves your success rate.

delay = 1
for attempt in range(5):
    resp = requests.get(url)
    if resp.ok:
        break
    time.sleep(delay)
    delay *= 2  # 1, 2, 4, 8, 16 seconds

Concurrency Limits

Parallel requests speed things up but multiply server load. Cap simultaneous connections with a semaphore so you never exceed a polite ceiling.

import threading
sem = threading.Semaphore(4)  # max 4 in flight

def fetch(url):
    with sem:
        requests.get(url)

Scheduling Off-Peak

Run heavy jobs during the site's low-traffic hours (often overnight in the host's timezone). Combined with throttling, this minimizes your footprint and reduces the chance of disruption.

Caching to Avoid Re-Fetching

The kindest request is the one you never send. Cache responses locally so re-running a job does not re-hit pages you already have. Only fetch what is new or stale.

import os
if not os.path.exists(cache_path):
    resp = requests.get(url)
    open(cache_path, 'w').write(resp.text)
html = open(cache_path).read()

Quick Check

Test your understanding of respectful crawling.

Recap

You learned to crawl respectfully: honor Crawl-delay, add randomized delays, use token buckets, react to 429 with backoff, cap concurrency, and schedule off-peak.

Polite pacing keeps your scraper sustainable and your access intact.

Gratis para empezar

Aprende Python con un tutor de IA — gratis

Escribe y ejecuta código real en tu navegador, obtén ayuda instantánea de un tutor de IA disponible 24/7 y continúa donde lo dejaste en la web o en la aplicación.

Cursos
12
Lecciones
48

Preguntas frecuentes

¿La lección «Limitación de velocidad y rastreo respetuoso» es gratis?

Sí — el texto completo de «Limitación de velocidad y rastreo respetuoso» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Web Scraping & Bots, actualiza a CoddyKit PRO. El curso de Web Scraping & Bots incluye 4 lecciones en total.

¿Qué aprenderé en «Limitación de velocidad y rastreo respetuoso»?

Aprenda a regular las solicitudes, respetar crawl-delay y evitar sobrecargar los servidores para que su scraping sea ético y sostenible. Practicas Web Scraping & Bots con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Web Scraping & Bots?

No se requiere experiencia previa. Web Scraping & Bots en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.

¿Cuánto tiempo toma la lección «Limitación de velocidad y rastreo respetuoso»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Web Scraping & Bots?

Sí. Cada lección de Web Scraping & Bots incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Comprensión de Robots.txt
  2. Términos del servicio y derechos de autor
  3. Prácticas éticas de scraping
  4. Limitación de velocidad y rastreo respetuoso
← Volver a Web Scraping & Bots