Foros Python

Versión completa: Coger datos de api esios luz
Actualmente estas viendo una versión simplificada de nuestro contenido. Ver la versión completa con el formato correcto.
Hola,

Por favor, te comento un poco porque he probado hacer scraping, tambien con
codigo html y javascript. He probado con una herramienta de github,
creo que tambien he mirado phyton.

Necesitaria los **precios hora** como en esta web www.tarifaluzhora.es, y tambien una **grafica** que tiene abajo.

Probé este codigo html en mi web que me dijo la ia, pero no funciona.

Qué habría que hacer?

Un saludo, gracias.
----

Código:
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Precios de la Luz</title>
    <style>
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: center;
        }
        th {
            background-color: #f2f2f2;
        }
        .highlight {
            color: red; /* Cambia esto según sea necesario para el
precio más alto */
        }
    </style>
</head>
<body>
    <h1>Precios de la Luz</h1>
    Precio ahora mismo: <strong id="current-price">Cargando...</strong><br>
    Precio medio del día: <strong id="average-price">Cargando...</strong><br>
    Precio más bajo del día: <strong id="lowest-price"
class="highlight">Cargando...</strong><br>
    Precio más alto del día: <strong id="highest-price"
class="highlight">Cargando...</strong><br>

    <h2>Precios por Hora</h2>
    <table id="price-table">
        <thead>
            <tr>
                <th>Hora</th>
                <th>Precio (€/kWh)</th>
            </tr>
        </thead>
        <tbody>
            <!-- Aquí se añadirán dinámicamente las filas de precios
por hora -->
        </tbody>
    </table>
    <p>Datos extraídos de la Red Eléctrica de España. Precio medio del
día: Media aritmética de los precios del día en función del tipo de
tarifa.</p>

    <script>
        async function fetchPrices() {
            const date = new Date();
            const startDate = date.toISOString().split('T')[0]; //
Fecha de hoy en formato YYYY-MM-DD
            const endDate = date.toISOString().split('T')[0]; // Fecha
de hoy en formato YYYY-MM-DD

            const url =
`https://api.esios.ree.es/indicators/1013?start_date=${startDate}T00:00:00&end_date=${endDate}T23:59:59`;

            try {
                const response = await fetch(url, {
                    headers: {
                        'Authorization': 'Token
mi token' //
Tu token
                    }
                });

                if (!response.ok) {
                    throw new Error('Error en la red');
                }

                const data = await response.json();

                // Obtener precios y actualizar el HTML
                const currentPrices = data.indicator.values[0]; // El
primer valor es el actual
                document.getElementById('current-price').innerText =
`${currentPrices.value}€/kWh`;
                document.getElementById('average-price').innerText =
`${currentPrices.average}€/kWh`;
                document.getElementById('lowest-price').innerText =
`${currentPrices.min}€/kWh`;
                document.getElementById('highest-price').innerText =
`${currentPrices.max}€/kWh`;

                // Actualiza la tabla de precios por hora
                const tableBody =
document.getElementById('price-table').getElementsByTagName('tbody')[0];
                tableBody.innerHTML = ''; // Limpiar tabla antes de
agregar nuevas filas

                data.indicator.values.forEach((value) => {
                    const row = document.createElement('tr');
                    const hour = new
Date(value.datetime).toLocaleTimeString([], { hour: '2-digit', minute:
'2-digit' });
                    row.innerHTML =
`<td>${hour}</td><td>${value.value}€/kWh</td>`;
                    tableBody.appendChild(row);
                });
            } catch (error) {
                console.error('Error al fetch los precios:', error);
            }
        }

        // Llama a la función al cargar la página
        fetchPrices();
    </script>
</body>
</html>

Un saludo, gracias.
Tienes que installar las librerias requests y BeatifulSoup.


Y corres este codigo, para que te de una idea:

Código:
import requests
from bs4 import BeautifulSoup

page = requests.get('https://tarifaluzhora.es/')


# print(page.text)

soup = BeautifulSoup(page.text, 'html.parser')

# print(soup.prettify)

items = soup.find_all('div', class_='row row--center')

for item in items:
    spans = item.find_all('span')
    if(len(spans) == 2):
        hour = spans[0].string
        price = spans[1].string
        price = price.replace('\t', '')
        price = price.replace('\n', ' ')
        print(f"Hour: {hour} and Price {price}")


El resultado seria:

Código:
Hour: 00:00 - 01:00 and Price 0.1597 €/kWh
Hour: 01:00 - 02:00 and Price 0.1525 €/kWh
Hour: 02:00 - 03:00 and Price 0.1483 €/kWh
Hour: 03:00 - 04:00 and Price 0.1476 €/kWh
Hour: 04:00 - 05:00 and Price 0.1397 €/kWh
Hour: 05:00 - 06:00 and Price 0.1369 €/kWh
Hour: 06:00 - 07:00 and Price 0.1428 €/kWh
Hour: 07:00 - 08:00 and Price 0.1529 €/kWh
Hour: 08:00 - 09:00 and Price 0.173 €/kWh
Hour: 09:00 - 10:00 and Price 0.1612 €/kWh
Hour: 10:00 - 11:00 and Price 0.1966 €/kWh
Hour: 11:00 - 12:00 and Price 0.1804 €/kWh
Hour: 12:00 - 13:00 and Price 0.176 €/kWh
Hour: 13:00 - 14:00 and Price 0.1756 €/kWh
Hour: 14:00 - 15:00 and Price 0.1239 €/kWh
Hour: 15:00 - 16:00 and Price 0.1228 €/kWh
Hour: 16:00 - 17:00 and Price 0.123 €/kWh
Hour: 17:00 - 18:00 and Price 0.1379 €/kWh
Hour: 18:00 - 19:00 and Price 0.2183 €/kWh
Hour: 19:00 - 20:00 and Price 0.2274 €/kWh
Hour: 20:00 - 21:00 and Price 0.2315 €/kWh
Hour: 21:00 - 22:00 and Price 0.2645 €/kWh
Hour: 22:00 - 23:00 and Price 0.1803 €/kWh
Hour: 23:00 - 24:00 and Price 0.1749 €/kWh
Hola,

Por favor, ya lo he traducido: 

--

import requests
from bs4 import BeautifulSoup

try:
    # Intentamos hacer la solicitud HTTP
    page = requests.get('https://tarifaluzhora.es/')
    page.raise_for_status()  # Verifica si hubo algún error en la solicitud (como un 404)
except requests.exceptions.RequestException as e:
    print(f"Error en la solicitud HTTP: {e}")
    input("Presiona Enter para salir...")
    exit()

try:
    # Intentamos analizar el contenido HTML
    soup = BeautifulSoup(page.text, 'html.parser')

    # Buscamos los elementos 'div' de interés
    items = soup.find_all('div', class_='row row--center')
   
    for item in items:
        spans = item.find_all('span')
        if len(spans) == 2:
            hora = spans[0].string  # Cambié "hour" por "hora"
            precio = spans[1].string  # Cambié "price" por "precio"
            precio = precio.replace('\t', '').replace('\n', ' ')
            print(f"Hora: {hora} y Precio: {precio}")
except Exception as e:
    print(f"Error al analizar el contenido de la página: {e}")

input("Presiona Enter para salir...")

--

Por favor, ahora necesito subirlo a una pagina web.  Qué necesitaria?

Un saludo, gracias.
Tienes dos opciones:

1-) Usando a python application server Django o Flask. Pero esto requeriria que el servidor donde pongas el codigo pueda correr Python.

2-) Modificando el programa para crear un text file con los datos extraidos y utilizar Javascript para crear la table dinamicamente leyendo este file.
El Webserver no necesataria Python pero tendras que update la text file, digamos una vez al dia manualmente o creando un schedule automatizado para subir la text file.

Dime cual escoges, y vere si te puedo ayudar.


Salu2