Skip to main content

Librería Python para acceder a datos públicos del Congreso de los Diputados de España (diputados, votaciones, iniciativas, intervenciones).

Project description

congreso-ia

PyPI version Python 3.9+ License: MIT

Libreria Python para acceder a datos publicos del Congreso de los Diputados de Espana. Extrae diputados, votaciones, iniciativas e intervenciones del portal de Open Data oficial.

Instalacion

pip install congreso-ia

Uso rapido

API Python

from congreso_ia import CongressClient

client = CongressClient()

# Obtener todos los diputados activos
deputies = client.get_deputies()
print(f"{len(deputies)} diputados")

# Filtrar por partido
pp_deputies = client.get_deputies(party="PP")

# Obtener votaciones recientes
votes = client.get_votes()

# Obtener iniciativas
initiatives = client.get_initiatives()

# Buscar intervenciones de un diputado
interventions = client.get_interventions(speaker="Pedro Sanchez")
print(f"{len(interventions)} intervenciones")

# Filtrar por organo y fecha
from datetime import date
pleno = client.get_interventions(
    speaker="Feijoo",
    organ="Pleno",
    start_date=date(2024, 1, 1)
)

Ejecucion paralela con rate limiting

Para busquedas masivas, usa el modulo de concurrencia que controla la tasa de peticiones:

from congreso_ia import CongressClient, parallel_fetch

client = CongressClient()

# Buscar intervenciones de multiples diputados en paralelo
speakers = ["Sanchez", "Feijoo", "Abascal", "Diaz"]

results = parallel_fetch(
    func=lambda s: client.get_interventions(speaker=s),
    items=speakers,
    max_workers=4,           # Threads concurrentes
    requests_per_second=2.0, # Rate limit
    on_progress=lambda done, total, r: print(f"{done}/{total}")
)

for r in results:
    if r.success:
        print(f"{r.item}: {len(r.result)} intervenciones")

Exportar a DataFrame

from congreso_ia import interventions

# Obtener como pandas DataFrame
df = interventions.fetch(speaker="Abascal", as_df=True)
print(df.head())

# Exportar a CSV
df.to_csv("intervenciones_abascal.csv", index=False)

CLI

# Descargar votaciones recientes
congreso scrape votes --latest

# Descargar intervenciones de una legislatura
congreso scrape interventions --legislature 15

# Exportar a diferentes formatos
congreso scrape votes --format parquet
congreso scrape votes --format csv

Datos disponibles

Recurso Metodo Campos principales
Diputados get_deputies() nombre, partido, circunscripcion, grupo, email, avatar_url
Votaciones get_votes() fecha, titulo, resultado, votos individuales
Iniciativas get_initiatives() titulo, tipo, autor, expediente
Intervenciones get_interventions() orador, fecha, organo, tema, video_url, pdf_url

Filtros disponibles

Diputados

  • party: Filtrar por partido (ej. "PP", "PSOE")
  • constituency: Filtrar por circunscripcion (ej. "Madrid")

Votaciones

  • deputy: Filtrar por nombre de diputado
  • party: Filtrar por partido

Intervenciones

  • speaker: Nombre del orador (busqueda parcial)
  • organ: Tipo de organo ("Pleno", "Comision")
  • legislature: Numero de legislatura
  • start_date / end_date: Rango de fechas

Rate Limiting

El modulo concurrent proporciona control de tasa para no sobrecargar el servidor:

from congreso_ia import RateLimiter

# Crear rate limiter: max 2 req/s, rafaga de 5
limiter = RateLimiter(requests_per_second=2.0, burst=5)

# Usar como context manager
with limiter:
    response = make_request()

# O manualmente
limiter.acquire()
response = make_request()

Fuentes de datos

Los datos provienen del portal de Open Data del Congreso:

  • Diputados: congreso.es/es/opendata/diputados
  • Votaciones: congreso.es/es/opendata/votaciones
  • Iniciativas: congreso.es/es/opendata/iniciativas
  • Intervenciones: congreso.es/es/opendata/intervenciones

Ejemplos

Ver la carpeta examples/ para mas ejemplos:

python examples/fetch_deputies.py
python examples/fetch_votes.py
python examples/fetch_interventions.py
python examples/parallel_interventions.py

Desarrollo

# Clonar repositorio
git clone https://github.com/congreso-ia/congreso-ia-scraper.git
cd congreso-ia-scraper

# Instalar en modo desarrollo
pip install -e ".[dev]"

# Ejecutar tests
pytest

# Linter
ruff check .

Disclaimer Legal

Este proyecto no es una fuente oficial del Congreso de los Diputados. Es una herramienta de codigo abierto que utiliza exclusivamente fuentes de datos publicos del portal de Open Data. El uso de esta herramienta debe cumplir con los terminos de servicio de la web oficial del Congreso.

Licencia

Distribuido bajo la licencia MIT. Ver LICENSE para mas informacion.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

congreso_ia-0.1.0.tar.gz (19.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

congreso_ia-0.1.0-py3-none-any.whl (22.0 kB view details)

Uploaded Python 3

File details

Details for the file congreso_ia-0.1.0.tar.gz.

File metadata

  • Download URL: congreso_ia-0.1.0.tar.gz
  • Upload date:
  • Size: 19.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.5

File hashes

Hashes for congreso_ia-0.1.0.tar.gz
Algorithm Hash digest
SHA256 98db248de89ff1aea561b3f7aa2b342ef8eecafac7a974ea12e5cb63decf52ce
MD5 cb26b59ab26e76067d2d611834774067
BLAKE2b-256 0a9756fb1235a6e6daa05b0d494fb8016c022f48d86ee35a4ca72ac1bf60bf31

See more details on using hashes here.

File details

Details for the file congreso_ia-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: congreso_ia-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 22.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.5

File hashes

Hashes for congreso_ia-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 bdac104217a4c9b5789caa240cb40b713a256144fb083f2c320b19d3d147860e
MD5 97f0343b6891d34cd4501609d29b74ac
BLAKE2b-256 bed3e949d01b8753e1177e7356afb26f3569ec305d09b8852e23d84a1cc1f277

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page