Web Scraping & Bots · Lección

Registro y manejo de errores para bots

Cree bots sencillos y resistentes incorporando registros estructurados y un manejo controlado de errores para que los fallos sean visibles y recuperables.

Lección 4 de 413 pasos

Registro y manejo de errores para bots 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 Bots Need Logs

A bot runs unattended, often on a schedule. When something breaks, you are not watching. Logging leaves a trail so you can diagnose what happened after the fact.

Without logs, a silent failure can go unnoticed for days.

print() Is Not Logging

Beginners use print(), but it has no levels, no timestamps, and no easy way to redirect to a file. Python's logging module solves all of this.

print('something happened')  # no level, no time, hard to manage

Setting Up Logging

Configure logging once at startup. Set a format with a timestamp and a level, and choose where output goes.

import logging

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s %(levelname)s %(message)s'
)
log = logging.getLogger('bot')
log.info('Bot started')

Log Levels

Levels let you control verbosity:

  • DEBUG detailed tracing.
  • INFO normal progress.
  • WARNING something odd but recoverable.
  • ERROR an operation failed.
  • CRITICAL the bot cannot continue.
log.debug('fetched 12 rows')
log.warning('retrying after timeout')
log.error('login failed')

Logging to a File

For unattended bots, write logs to a file so you can review them later. A rotating handler caps file size.

from logging.handlers import RotatingFileHandler

handler = RotatingFileHandler('bot.log', maxBytes=1_000_000, backupCount=3)
log.addHandler(handler)

Catching Exceptions

Wrap risky operations in try/except so one failure does not crash the whole run. Log the error with context.

try:
    submit_form(data)
except Exception as e:
    log.error('form submission failed: %s', e)

Logging Full Tracebacks

Use log.exception inside an except block to capture the full stack trace, which is invaluable for debugging.

try:
    risky()
except Exception:
    log.exception('unexpected error in risky()')

Retrying Transient Failures

Network blips are common. Catch them and retry a few times before giving up, logging each attempt.

for attempt in range(3):
    try:
        fetch()
        break
    except ConnectionError:
        log.warning('attempt %d failed, retrying', attempt + 1)
else:
    log.error('all attempts failed')

Failing Loudly

Silent failures are dangerous. For critical errors, escalate: send an alert email, write a marker file, or exit with a non-zero code so a scheduler notices.

import sys
if not data:
    log.critical('no data scraped, aborting')
    sys.exit(1)

Clean Shutdown

Always release resources even on error. A finally block (or context managers) guarantees browsers close and files flush regardless of what went wrong.

try:
    run_bot()
finally:
    driver.quit()
    log.info('bot finished')

Structured Logging Context

Attach context to each log line, such as the current URL or item id, so when you scan a long log you immediately know which record a message refers to.

log.info('scraped item %s from %s', item_id, url)

Quick Check

Test your understanding of bot logging and error handling.

Recap

You learned to make simple bots resilient: use the logging module instead of print, choose appropriate levels, log to rotating files, catch and log exceptions with tracebacks, retry transient errors, fail loudly on critical issues, and shut down cleanly.

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 «Registro y manejo de errores para bots» es gratis?

Sí — el texto completo de «Registro y manejo de errores para bots» 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 «Registro y manejo de errores para bots»?

Cree bots sencillos y resistentes incorporando registros estructurados y un manejo controlado de errores para que los fallos sean visibles y recuperables. 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 «Registro y manejo de errores para bots»?

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. Definición de objetivos de bots
  2. Automatización del envío de formularios sencillos
  3. Programación de tareas básicas
  4. Registro y manejo de errores para bots
← Volver a Web Scraping & Bots