{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Práctica: extracción de datos de una tienda de juegos\n",
        "\n",
        "En esta práctica utilizarás **BeautifulSoup** para extraer información de `tienda_juegos.html`. Después guardarás los datos obtenidos en CSV y JSON.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# 1. Extraer los juegos del HTML"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "268df732",
      "metadata": {},
      "outputs": [],
      "source": [
        "#Coger el contenido jhuegos.html\n",
        "from bs4 import BeautifulSoup\n",
        "with open(\"tienda_juegos.html\", \"r\", encoding=\"utf-8\") as file:\n",
        "    contenido = file.read()\n",
        "\n",
        "soup = BeautifulSoup(contenido, \"html.parser\")\n",
        "print(soup.prettify())"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "id": "9b896b99",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Juegos Destacados\n",
            "The Legend of Zelda: Breath of the Wild\n",
            "59.99€\n",
            "{'categoria': 'Juegos Destacados', 'id': '001', 'nombre': 'The Legend of Zelda: Breath of the Wild', 'precio': 59.99, 'imagen': 'https://assets.nintendo.com/image/upload/c_fill,w_1200/q_auto:best/f_auto/dpr_2.0/ncom/en_US/games/switch/t/the-legend-of-zelda-breath-of-the-wild-switch/hero', 'texto_imagen': 'Imagen de Zelda', 'enlace_compra': '/comprar/zelda', 'titulo_enlace': 'Comprar Zelda'}\n",
            "The Witcher 3: Wild Hunt\n",
            "39.99€\n",
            "{'categoria': 'Juegos Destacados', 'id': '002', 'nombre': 'The Witcher 3: Wild Hunt', 'precio': 39.99, 'imagen': 'https://th.bing.com/th/id/OIP.7wiL2rFVFgFUFB-jiYiSrwHaEK?w=321&h=181&c=7&r=0&o=5&dpr=1.3&pid=1.7', 'texto_imagen': 'Imagen de Witcher 3', 'enlace_compra': '/comprar/witcher3', 'titulo_enlace': 'Comprar Witcher 3'}\n",
            "Cyberpunk 2077\n",
            "49.99€\n",
            "{'categoria': 'Juegos Destacados', 'id': '003', 'nombre': 'Cyberpunk 2077', 'precio': 49.99, 'imagen': 'https://th.bing.com/th/id/OIP.E4XWyisiUY34i1GpZAWUcAHaEK?rs=1&pid=ImgDetMain', 'texto_imagen': 'Imagen de Cyberpunk 2077', 'enlace_compra': '/comprar/cyberpunk2077', 'titulo_enlace': 'Comprar Cyberpunk 2077'}\n",
            "Nuevos Lanzamientos\n",
            "Elden Ring\n",
            "69.99€\n",
            "{'categoria': 'Nuevos Lanzamientos', 'id': '004', 'nombre': 'Elden Ring', 'precio': 69.99, 'imagen': 'https://th.bing.com/th/id/OSK.HEROCLICKTHROUGHeJ8C-vOc8Kozl_udnetJoq3gAha4kA7vpBS_ZodhUe8?rs=1&pid=ImgDetMain', 'texto_imagen': 'Imagen de Elden Ring', 'enlace_compra': '/comprar/elden-ring', 'titulo_enlace': 'Comprar Elden Ring'}\n",
            "Resident Evil Village\n",
            "49.99€\n",
            "{'categoria': 'Nuevos Lanzamientos', 'id': '005', 'nombre': 'Resident Evil Village', 'precio': 49.99, 'imagen': 'https://www.trustedreviews.com/wp-content/uploads/sites/54/2021/01/Resident-Evil-Village-Chris-Keyart.jpg', 'texto_imagen': 'Imagen de Resident Evil Village', 'enlace_compra': '/comprar/resident-evil-village', 'titulo_enlace': 'Comprar Resident Evil Village'}\n",
            "Juegos en Oferta\n",
            "Hades\n",
            "19.99€\n",
            "{'categoria': 'Juegos en Oferta', 'id': '006', 'nombre': 'Hades', 'precio': 19.99, 'imagen': 'https://static.actugaming.net/media/2018/12/Hades-Pack-Art-1.jpg', 'texto_imagen': 'Imagen de Hades', 'enlace_compra': '/comprar/hades', 'titulo_enlace': 'Comprar Hades'}\n",
            "Hollow Knight\n",
            "9.99€\n",
            "{'categoria': 'Juegos en Oferta', 'id': '007', 'nombre': 'Hollow Knight', 'precio': 9.99, 'imagen': 'https://cdn02.nintendo-europe.com/media/images/11_square_images/games_18/wii_u_download_software_3/SQ_WiiUDS_HollowKnight.jpg', 'texto_imagen': 'Imagen de Hollow Knight', 'enlace_compra': '/comprar/hollow-knight', 'titulo_enlace': 'Comprar Hollow Knight'}\n"
          ]
        }
      ],
      "source": [
        "secciones = soup.find_all(\"section\")\n",
        "\n",
        "juegos_dict = []\n",
        "for seccion in secciones:\n",
        "    \n",
        "    h2 = seccion.find(\"h2\").get_text(strip=True)\n",
        "    print(h2)\n",
        "    juegos = seccion.find_all(\"div\",class_=\"juego\")\n",
        "    for juego in juegos:\n",
        "        h3 = juego.find(\"h3\").get_text(strip=True)\n",
        "        print(h3)\n",
        "        precio=juego.find(\"p\", class_=\"precio\").get_text(strip=True)\n",
        "        print(precio)\n",
        "        imagen = juego.find(\"img\")\n",
        "        enlace = juego.find(\"a\", class_=\"comprar-btn\")\n",
        "\n",
        "        juego_dict = {\n",
        "                    \"categoria\": h2,\n",
        "                    \"id\": juego[\"data-id\"],\n",
        "                    \"nombre\": h3,\n",
        "                    \"precio\": float(precio.replace(\"€\", \"\")),\n",
        "                    \"imagen\": imagen[\"src\"],\n",
        "                    \"texto_imagen\": imagen[\"alt\"],\n",
        "                    \"enlace_compra\": enlace[\"href\"],\n",
        "                    \"titulo_enlace\": enlace[\"title\"]\n",
        "                }\n",
        "        juegos_dict.append(juego_dict)\n",
        "        print(juego_dict)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "8cc3f61f",
      "metadata": {},
      "source": [
        "# 2. Crear un fichero CSV con los datos extraidos"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 9,
      "id": "afdd7631",
      "metadata": {},
      "outputs": [],
      "source": [
        "import csv\n",
        "\n",
        "#creo csv\n",
        "with open(\"juego.csv\", \"w\", encoding=\"utf-8\", newline=\"\") as fichero:\n",
        "    campos = [\"categoria\", \"id\", \"nombre\", \"precio\",\"imagen\", \"texto_imagen\", \"enlace_compra\", \"titulo_enlace\"]\n",
        "    micsv = csv.DictWriter(fichero, fieldnames=campos)\n",
        "    micsv.writeheader()\n",
        "    micsv.writerows(juegos_dict)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "074b7ff2",
      "metadata": {},
      "source": [
        "# 3. Crear un JSON con los datos extraidos\n",
        "\n",
        "Crear un fichero JSON con los datos extraidos"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 11,
      "metadata": {},
      "outputs": [],
      "source": [
        "import json\n",
        "\n",
        "with open(\"juegos.json\", \"w\", encoding=\"utf-8\") as fichero:\n",
        "    json.dump(juegos_dict, fichero, ensure_ascii=False, indent=4)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "d4aa0e7b",
      "metadata": {},
      "source": [
        "# 4 Crear un nuevo json con un nivel Categoría y debajo sus juego con sus datos\n",
        "juegos_anidados = {\n",
        "    \"Juegos Destacados\": [\n",
        "        {\"nombre\": \"Zelda\", \"precio\": 59.99},\n",
        "        {\"nombre\": \"The Witcher\", \"precio\": 39.99}\n",
        "    ]\n",
        "}\n",
        "\n",
        "Tener en cuenta la estructura de datos:  \n",
        "    **{} crea un diccionario.** Guarda datos mediante pares clave: valor  \n",
        "    **[] crea una lista.** Guarda varios elementos ordenados.    \n",
        "\n",
        "diccionario {lista[diccionario]}\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "8e4ee2dd",
      "metadata": {},
      "outputs": [],
      "source": [
        "#Dicionario superior: \"Juegos Destacados\",  \"Nuevos Lanzamientos\", \"Juegos en Oferta\" cada uno de ellos lo guardaremos en h2\n",
        "juegos_anidados = {}\n",
        "\n",
        "for seccion in secciones:\n",
        "    h2 = seccion.find(\"h2\").get_text(strip=True)\n",
        "    \n",
        "    juegos = seccion.find_all(\"div\",class_=\"juego\")\n",
        "    for juego in juegos:\n",
        "        h3 = juego.find(\"h3\").get_text(strip=True)\n",
        "       \n",
        "        precio=juego.find(\"p\", class_=\"precio\").get_text(strip=True)\n",
        "       \n",
        "        imagen = juego.find(\"img\")\n",
        "        enlace = juego.find(\"a\", class_=\"comprar-btn\")\n",
        "\n",
        "        #Dicionario interior:  \"nombre\": \"The Legend of Zelda: Breath of the Wild\", \"precio\": 59.99\" ...\n",
        "        juego_dict = {                    \n",
        "                    \"id\": juego[\"data-id\"],\n",
        "                    \"nombre\": h3,\n",
        "                    \"precio\": float(precio.replace(\"€\", \"\")),\n",
        "                    \"imagen\": imagen[\"src\"],\n",
        "                    \"texto_imagen\": imagen[\"alt\"],\n",
        "                    \"enlace_compra\": enlace[\"href\"],\n",
        "                    \"titulo_enlace\": enlace[\"title\"]\n",
        "                }\n",
        "        \n",
        "        # Si no existe la categoria la crea vacia\n",
        "        # juegos_anidados = {\n",
        "        #        \"Juegos Destacados\": []\n",
        "        #    }\n",
        "        if h2 not in juegos_anidados:\n",
        "            juegos_anidados[h2] = []\n",
        "\n",
        "        juegos_anidados[h2].append(juego_dict)\n",
        "\n",
        "        "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 14,
      "id": "c2f3f0b8",
      "metadata": {},
      "outputs": [],
      "source": [
        "import json\n",
        "\n",
        "with open(\"juegos_anidados.json\", \"w\", encoding=\"utf-8\") as fichero:\n",
        "    json.dump(juegos_anidados, fichero, ensure_ascii=False, indent=4)"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": ".venv (3.14.7.final.0)",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.14.7"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
