Scrapping

This commit is contained in:
Andrés Moran 2024-12-11 03:42:22 +01:00
parent d697b3f7cf
commit d6d750ae33
6 changed files with 110 additions and 5 deletions

Binary file not shown.

Binary file not shown.

21
app/panel_izquierdo.py Normal file
View File

@ -0,0 +1,21 @@
import tkinter as tk
import threading
from app import scraping
class PanelIzquierdo:
def __init__(self, frame, text_widget):
# Asociar el frame del panel izquierdo
self.frame = frame
self.frame.configure(bg="lightblue", width=200)
self.frame.grid_propagate(False)
self.frame.columnconfigure(0, weight=1)
boton_scrapping = tk.Button(
frame,
text="Iniciar Scrapping",
command=lambda: threading.Thread(
target=scraping.iniciar_scraping_y_insercion,
args=("https://www.amazon.es/", text_widget)
).start()
)
boton_scrapping.pack(pady=5)

View File

@ -0,0 +1,79 @@
import requests
from bs4 import BeautifulSoup
import threading
import mysql.connector
from queue import Queue
def obtener_conexion():
try:
conexion = mysql.connector.connect(
host='localhost',
port=3306,
user='root',
password='1234',
database='scraping'
)
return conexion
except mysql.connector.Error as err:
print(f"Error al conectar con la base de datos: {err}")
return None
# Función para extraer enlaces y enviarlos a la cola
def extraer_enlaces(url, cola, text_widget):
try:
respuesta = requests.get(url)
if respuesta.status_code == 200:
contenido_html = respuesta.text
soup = BeautifulSoup(contenido_html, 'html.parser')
for enlace in soup.find_all('a', href=True):
enlace_str = enlace['href']
cola.put(enlace_str)
if text_widget:
text_widget.insert('end', enlace_str + "\n")
print("Extracción de enlaces completada.")
else:
print(f"Error al acceder a la URL: {respuesta.status_code}")
except requests.exceptions.RequestException as e:
print(f"Error durante la solicitud HTTP: {e}")
# Función para insertar enlaces en la base de datos
def insertar_enlaces_mysql(cola):
conexion = obtener_conexion()
if not conexion:
return
cursor = conexion.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS enlaces (
id INT AUTO_INCREMENT PRIMARY KEY,
enlace VARCHAR(255) UNIQUE
)''')
while True:
enlace = cola.get()
if enlace == "FIN":
break
try:
cursor.execute("INSERT IGNORE INTO enlaces (enlace) VALUES (%s)", (enlace,))
conexion.commit()
print(f"Enlace insertado en la base de datos: {enlace}")
except mysql.connector.Error as err:
print(f"Error al insertar enlace: {err}")
cursor.close()
conexion.close()
print("Inserción en la base de datos finalizada.")
# Función para iniciar el scraping y la inserción en hilos
def iniciar_scraping_y_insercion(url, text_widget):
cola_enlaces = Queue()
hilo_scraping = threading.Thread(target=extraer_enlaces, args=(url, cola_enlaces, text_widget))
hilo_insercion = threading.Thread(target=insertar_enlaces_mysql, args=(cola_enlaces,))
hilo_scraping.start()
hilo_insercion.start()
hilo_scraping.join()
cola_enlaces.put("FIN")
hilo_insercion.join()

15
main.py
View File

@ -4,11 +4,14 @@ from tkinter import ttk # Importar el widget ttk
from tkinter import messagebox
from app import monitorization
from app import panel_derecho
from app import panel_izquierdo
from app import pomodoro
import threading
import time
import datetime
import psutil
from app import scraping
def update_time(status_bar):
while True:
@ -73,8 +76,6 @@ frame_derecho.grid(row=0, column=2, sticky="ns")
frame_izquierdo.grid_propagate(False)
frame_derecho.grid_propagate(False)
panel_izquierdo = panel_derecho.PanelDerecho(frame_derecho)
# Dividir el frame central en dos partes (superior variable e inferior fija)
frame_central.rowconfigure(0, weight=1) # Parte superior, tamaño variable
frame_central.rowconfigure(1, weight=0) # Parte inferior, tamaño fijo
@ -102,12 +103,13 @@ style.configure("CustomNotebook.TNotebook.Tab", font=("Arial", 12, "bold"))
notebook = ttk.Notebook(frame_superior, style="CustomNotebook.TNotebook")
notebook.pack(fill="both", expand=True)
# Crear cinco solapas
for i in range(1, 6):
tab = ttk.Frame(notebook)
if i == 1:
notebook.add(tab, text="Scrapping", padding=4)
text_scrapping = tk.Text(tab, wrap="word")
text_scrapping.pack(fill="both", expand=True)
elif i == 2: # Identificar la solapa 2
notebook.add(tab, text="Pomodoro", padding=4)
pomodoro.PomodoroTimer(tab)
@ -125,8 +127,6 @@ for i in range(1, 6):
# Usar pack para alinear los labels horizontalmente
label_cpu_used = tk.Label(barra_estado, text="CPU: 0%", font=("Helvetica", 11), bd=1, fg="blue", relief="sunken", anchor="w", width=20, padx=10)
label_ram_used = tk.Label(barra_estado, text="RAM: 0%", font=("Helvetica", 11), bd=1, fg="blue", relief="sunken", anchor="w", width=20, padx=10)
label_pc_battery = tk.Label(barra_estado, text="Temperatura CPU: ", font=("Helvetica", 11), bd=1, fg="blue", relief="sunken", anchor="w", width=20, padx=10)
@ -140,6 +140,7 @@ label_network_used.pack(side="left", fill="x", expand=True)
label_fecha_hora.pack(side="right", fill="x", expand=True)
#Monitorizacion barra horizontal de abajo
update_thread = threading.Thread(target=update_time, args=(label_fecha_hora,))
update_thread.daemon = True
update_thread.start()
@ -160,6 +161,10 @@ thread_network_used_monitor = threading.Thread(target=monitorization.monitor_net
thread_network_used_monitor.daemon = True
thread_network_used_monitor.start()
#Lados verticulas
panel_d = panel_derecho.PanelDerecho(frame_derecho)
panel_i = panel_izquierdo.PanelIzquierdo(frame_izquierdo, text_scrapping)
# Ejecución de la aplicación
root.mainloop()