Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added artistas_con_mas_canciones.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added cantidad_canciones_por_ano.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added spotify_analysis.db
Binary file not shown.
114 changes: 114 additions & 0 deletions src/app.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,122 @@

import os
import io
from bs4 import BeautifulSoup
import requests
import time
import sqlite3
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

## Paso 1: Instalación de dependencias

#pip install pandas requests lxml
# pip install matplotlib seaborn

## Paso 2: Descargar HTML

with open("/workspaces/web-scraping-project-tutorial_Sahid_Leal/src/spotify_html.mhtml", "r", encoding="utf-8") as file:
html = file.read()

## Paso 3: Transforma el HTML

html = io.StringIO(html[:100000])
table = pd.read_html(html)[0]
print(table.head())

## Paso 4: Procesa el DataFrame

df = pd.DataFrame(table)
print(df.head())
print(df.shape)

df_limpio = df.dropna(how="all") #para eliminar las filas que tienen todos los valores nulos
print(df_limpio.shape)

df['Release date'] = pd.to_datetime(df['Release date'], errors='coerce') # convertir la columna 'Release date' a tipo datetime, y si hay errores, se reemplazan con NaT (Not a Time)
df['Release date'] = df['Release date'].dt.strftime('%Y-%m-%d') #convertir la columna 'Release date' a formato de fecha 'YYYY-MM-DD'

print(df.head())

## Paso 5: Almacena los datos en sqlite

"""Crea una instancia vacía de la base de datos e incluye en ella los datos limpios, como vimos en el módulo de bases de datos. Una vez tengas una base de datos vacía:

1. Crea la tabla.
2. Inserta los valores.
3. Almacena (commit) los cambios.

con = sqlite3.connect("spotify_analysis.db")

con.execute(CREATE TABLE spotify_ranking_artist (
Rank INTEGER PRIMARY KEY NOT NULL,
Song TEXT NOT NULL,
"Artist(s)" TEXT NOT NULL,
"Streams (billions)" REAL NOT NULL,
Release_date TEXT NOT NULL,
"Ref." TEXT NOT NULL
))


con.commit()
con.close() #cierrar la conexión a la base de datos SQLite
"""


# Insertar los datos del DataFrame en la tabla de la base de datos SQLite

con = sqlite3.connect("spotify_analysis.db")

df_limpio.to_sql(
name="spotify_ranking_artist",
con=con,
if_exists="replace",
index=False,
)

print(f"Guardada la tabla spotify_ranking_artist con {len(df_limpio)} filas")

# Validar la carga leyendo una muestra desde la base de datos
table_proof = pd.read_sql_query("SELECT \"Artist(s)\" FROM spotify_ranking_artist", con)
print(table_proof)

con.commit()
con.close() # cerrar la conexión a la base de datos SQLite

## Paso 6: Visualiza los datos

# Top 10 canciones más reproducidas, recordemos que el df ya esta ordenado de manera descendente por 'Streams (billions)'

df_limpio.head(10).plot(x='Song', y='Streams (billions)', kind='bar', figsize=(12, 6), color='skyblue')
plt.title('Top 10 canciones más reproducidas en Spotify')
plt.xlabel('Canción')
plt.ylabel('Reproducciones (en miles de millones)')
plt.xticks(rotation=45, ha='right')
plt.tight_layout()
plt.savefig('top_10_canciones_mas_reproducidas.png')



# Cantidad de canciones por año de lanzamiento

df_limpio['Release date'] = pd.to_datetime(df_limpio['Release date'], errors='coerce') # Convertir a datetime
df_limpio['Year'] = df_limpio['Release date'].dt.year #se crea una nueva columna 'Year' a partir de la columna 'Release date'
df_limpio['Year'].value_counts().sort_index().plot(kind='bar', figsize=(12, 6), color='lightgreen') #se cuentan las canciones por año y se ordenan por año para graficarlas
plt.title('Cantidad de canciones por año de lanzamiento')
plt.xlabel('Año de lanzamiento')
plt.ylabel('Cantidad de canciones')
plt.xticks(rotation=45, ha='right')
plt.tight_layout()
plt.savefig('cantidad_canciones_por_ano.png')


# Artistas con mas canciones en el ranking

df_limpio['Artist(s)'].value_counts().plot(kind='bar', figsize=(12, 6), color='salmon') #se cuentan las canciones por artista y se ordenan por cantidad de canciones para graficarlas
plt.title('Artistas con más canciones en el ranking')
plt.xlabel('Artista')
plt.ylabel('Cantidad de canciones')
plt.xticks(rotation=45, ha='right')
plt.tight_layout()
plt.savefig('artistas_con_mas_canciones.png')
Binary file added src/artistas_con_mas_canciones.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added src/cantidad_canciones_por_ano.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading