diff --git a/Ejercicio04_WebScrapper/Main.py b/Ejercicio04_WebScrapper/Main.py index 037a9c9..aaffb7b 100644 --- a/Ejercicio04_WebScrapper/Main.py +++ b/Ejercicio04_WebScrapper/Main.py @@ -1,69 +1,97 @@ import os import threading import queue -import time from WebFileReader import WebFileReader -print("Directorio actual:", os.getcwd()) +# Ruta base de los archivos HTML +base_path = "EjerciciosConHilos/Ejercicio04_WebScrapper/resources/input_html" +output_dir = "EjerciciosConHilos/Ejercicio04_WebScrapper/resources/output" +output_file = os.path.join(output_dir, "extracted_links.txt") -# Inicializa colas para la comunciación entre hilos -data_queue = queue.Queue() +# Asegurarse de que la carpeta de salida existe +os.makedirs(output_dir, exist_ok=True) + +# Cola de enlaces pendientes de procesar y conjunto de enlaces ya procesados link_queue = queue.Queue() +processed_links = set() +lock = threading.Lock() # Para sincronizar el acceso a `processed_links` -# Instancia de WebFileReader -reader = WebFileReader() +# Instancia de WebFileReader para leer HTML y extraer enlaces +reader = WebFileReader(base_path=base_path) -# Hilo A: Lee el archivos HTML y los coloca en data_queue -def hilo_a(): - filenames = ["index.html", "1.html", "2.html"] - for filename in filenames: - print(f"[Hilo A] Leyendo archivo: {filename}") - content = reader.read_file(filename) +# Método adicional en WebFileReader para guardar los enlaces +def guardar_enlaces(enlaces): + """ + Guarda los enlaces extraídos en un archivo. + """ + with open(output_file, 'a', encoding='utf-8') as file: + for enlace in enlaces: + file.write(enlace + "\n") + print(f"[WebFileReader] Enlaces guardados en {output_file}") + +# Función que explora enlaces y descubre nuevos +def procesar_enlace(): + while True: + # Obtener un enlace de la cola + link = link_queue.get() + + # Si obtenemos None, significa que el procesamiento ha terminado + if link is None: + break + + # Marcar el enlace como procesado si no lo ha sido ya + with lock: + if link in processed_links: + link_queue.task_done() + continue + processed_links.add(link) + + print(f"[Hilo] Procesando enlace: {link}") + + # Combinar `base_path` con el nombre del archivo para obtener la ruta completa + full_path = os.path.join(base_path, link) + + # Leer el contenido del archivo HTML + content = reader.read_file(link) if content: - data_queue.put((filename, content)) - time.sleep(1) #Simulacion del tiempo de espera + # Extraer los enlaces internos de este archivo + new_links = reader.extract_links(content) + + # Guardar los enlaces extraídos + guardar_enlaces(new_links) + + # Colocar nuevos enlaces en la cola si aún no han sido procesados + for new_link in new_links: + # Normalizar solo el nombre del archivo y agregar a la cola + normalized_link = os.path.normpath(new_link) + + with lock: + if normalized_link not in processed_links: + link_queue.put(normalized_link) -# Hilo B: Extrae los enlaces del contenido HTML y los coloca en link_queue -def hilo_b(): - while True: - if not data_queue.empty(): - filename, html_content = data_queue.get() - print(f"[Hilo B] Extrayendo enlaces de: {filename}") - links = reader.extract_links(html_content) - for link in links: - link_queue.put(link) + # Marcar este enlace como procesado en la cola + link_queue.task_done() -# Hilo C: Guarda el contenido de los archivos en archivos de texto en la carpeta resources -def hilo_c(): - while True: - if not data_queue.empty(): - filename, html_content = data_queue.get() - save_path = f"EjerciciosConHilos/Ejercicio04_WebScrapper/resources/output/{filename.replace('.html', '')}_content.txt" - with open(save_path, 'w', encoding='utf-8') as file: - file.write(html_content) - print(f"[Hilo C] Guardando contenido de {filename} en {save_path}") +# Enlace inicial para comenzar el procesamiento (solo nombre de archivo) +initial_link = "index.html" +link_queue.put(initial_link) -# Hilo D: Guarda los enlaces extraídos en un archivo de texto para análisis -def hilo_d(): - while True: - if not link_queue.empty(): - link = link_queue.get() - with open("EjerciciosConHilos/Ejercicio04_WebScrapper/resources/output/extracted_links.txt", 'a', encoding='utf-8') as file: - file.write(link + "\n") - print(f"[Hilo D] Enlace guardado: {link}") +# Crear y lanzar los hilos para procesar los enlaces +num_threads = 4 # Ajusta el número de hilos según el sistema +threads = [] +for _ in range(num_threads): + thread = threading.Thread(target=procesar_enlace) + thread.start() + threads.append(thread) -thread_a = threading.Thread(target=hilo_a, daemon=True) -thread_b = threading.Thread(target=hilo_b, daemon=True) -thread_c = threading.Thread(target=hilo_c, daemon=True) -thread_d = threading.Thread(target=hilo_d, daemon=True) +# Esperar a que todos los enlaces en la cola se procesen +link_queue.join() -thread_a.start() -thread_b.start() -thread_c.start() -thread_d.start() +# Detener los hilos después de terminar el procesamiento +for _ in threads: + link_queue.put(None) # Insertar `None` para detener cada hilo -try: - while True: - time.sleep(1) -except KeyboardInterrupt: - print("Programa terminado") \ No newline at end of file +for thread in threads: + thread.join() + +print("Todos los enlaces han sido procesados.") diff --git a/Ejercicio04_WebScrapper/PruebaMain.py b/Ejercicio04_WebScrapper/PruebaMain.py new file mode 100644 index 0000000..037a9c9 --- /dev/null +++ b/Ejercicio04_WebScrapper/PruebaMain.py @@ -0,0 +1,69 @@ +import os +import threading +import queue +import time +from WebFileReader import WebFileReader + +print("Directorio actual:", os.getcwd()) + +# Inicializa colas para la comunciación entre hilos +data_queue = queue.Queue() +link_queue = queue.Queue() + +# Instancia de WebFileReader +reader = WebFileReader() + +# Hilo A: Lee el archivos HTML y los coloca en data_queue +def hilo_a(): + filenames = ["index.html", "1.html", "2.html"] + for filename in filenames: + print(f"[Hilo A] Leyendo archivo: {filename}") + content = reader.read_file(filename) + if content: + data_queue.put((filename, content)) + time.sleep(1) #Simulacion del tiempo de espera + +# Hilo B: Extrae los enlaces del contenido HTML y los coloca en link_queue +def hilo_b(): + while True: + if not data_queue.empty(): + filename, html_content = data_queue.get() + print(f"[Hilo B] Extrayendo enlaces de: {filename}") + links = reader.extract_links(html_content) + for link in links: + link_queue.put(link) + +# Hilo C: Guarda el contenido de los archivos en archivos de texto en la carpeta resources +def hilo_c(): + while True: + if not data_queue.empty(): + filename, html_content = data_queue.get() + save_path = f"EjerciciosConHilos/Ejercicio04_WebScrapper/resources/output/{filename.replace('.html', '')}_content.txt" + with open(save_path, 'w', encoding='utf-8') as file: + file.write(html_content) + print(f"[Hilo C] Guardando contenido de {filename} en {save_path}") + +# Hilo D: Guarda los enlaces extraídos en un archivo de texto para análisis +def hilo_d(): + while True: + if not link_queue.empty(): + link = link_queue.get() + with open("EjerciciosConHilos/Ejercicio04_WebScrapper/resources/output/extracted_links.txt", 'a', encoding='utf-8') as file: + file.write(link + "\n") + print(f"[Hilo D] Enlace guardado: {link}") + +thread_a = threading.Thread(target=hilo_a, daemon=True) +thread_b = threading.Thread(target=hilo_b, daemon=True) +thread_c = threading.Thread(target=hilo_c, daemon=True) +thread_d = threading.Thread(target=hilo_d, daemon=True) + +thread_a.start() +thread_b.start() +thread_c.start() +thread_d.start() + +try: + while True: + time.sleep(1) +except KeyboardInterrupt: + print("Programa terminado") \ No newline at end of file diff --git a/Ejercicio04_WebScrapper/WebFileReader.py b/Ejercicio04_WebScrapper/WebFileReader.py index 8b26a30..543d6c5 100644 --- a/Ejercicio04_WebScrapper/WebFileReader.py +++ b/Ejercicio04_WebScrapper/WebFileReader.py @@ -27,5 +27,3 @@ class WebFileReader: soup = BeautifulSoup(html_content, 'html.parser') links = [a['href'] for a in soup.find_all('a', href=True)] return links - - diff --git a/Ejercicio04_WebScrapper/__pycache__/WebFileReader.cpython-312.pyc b/Ejercicio04_WebScrapper/__pycache__/WebFileReader.cpython-312.pyc index de9ef43..6cddf68 100644 Binary files a/Ejercicio04_WebScrapper/__pycache__/WebFileReader.cpython-312.pyc and b/Ejercicio04_WebScrapper/__pycache__/WebFileReader.cpython-312.pyc differ diff --git a/Ejercicio04_WebScrapper/resources/input_html/1.html b/Ejercicio04_WebScrapper/resources/input_html/1.html index a818cc2..090f7db 100644 --- a/Ejercicio04_WebScrapper/resources/input_html/1.html +++ b/Ejercicio04_WebScrapper/resources/input_html/1.html @@ -3,9 +3,9 @@ Página 1 - + Ir a página 2
Volver - + \ No newline at end of file diff --git a/Ejercicio04_WebScrapper/resources/input_html/2.html b/Ejercicio04_WebScrapper/resources/input_html/2.html index 0635933..2404723 100644 --- a/Ejercicio04_WebScrapper/resources/input_html/2.html +++ b/Ejercicio04_WebScrapper/resources/input_html/2.html @@ -3,9 +3,11 @@ Página 2 - + Ir a página 1
Volver - + + + \ No newline at end of file diff --git a/Ejercicio04_WebScrapper/resources/input_html/index.html b/Ejercicio04_WebScrapper/resources/input_html/index.html index cf1c6dd..d4d2641 100644 --- a/Ejercicio04_WebScrapper/resources/input_html/index.html +++ b/Ejercicio04_WebScrapper/resources/input_html/index.html @@ -3,7 +3,7 @@ Inicio - + Ir a página 1 - + \ No newline at end of file diff --git a/Ejercicio04_WebScrapper/resources/output/1_content.txt b/Ejercicio04_WebScrapper/resources/output/1_content.txt deleted file mode 100644 index a818cc2..0000000 --- a/Ejercicio04_WebScrapper/resources/output/1_content.txt +++ /dev/null @@ -1,11 +0,0 @@ - - - - Página 1 - - - Ir a página 2 -
- Volver - - \ No newline at end of file diff --git a/Ejercicio04_WebScrapper/resources/output/extracted_links.txt b/Ejercicio04_WebScrapper/resources/output/extracted_links.txt index 0ca3f30..c61bee9 100644 --- a/Ejercicio04_WebScrapper/resources/output/extracted_links.txt +++ b/Ejercicio04_WebScrapper/resources/output/extracted_links.txt @@ -1,7 +1,16 @@ +1.html 2.html index.html 1.html index.html 1.html +2.html +index.html 1.html index.html +1.html +2.html +index.html +1.html +index.html +prueba diff --git a/Ejercicio04_WebScrapper/resources/output/index_content.txt b/Ejercicio04_WebScrapper/resources/output/index_content.txt deleted file mode 100644 index cf1c6dd..0000000 --- a/Ejercicio04_WebScrapper/resources/output/index_content.txt +++ /dev/null @@ -1,9 +0,0 @@ - - - - Inicio - - - Ir a página 1 - - \ No newline at end of file