Created
September 10, 2023 10:51
-
-
Save cargabsj175/903d5e9d95e51ed2da43e136e7593297 to your computer and use it in GitHub Desktop.
Genera un archivo con titulos H explorando las url de un dominio dado
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import requests | |
| from bs4 import BeautifulSoup | |
| import csv | |
| from urllib.parse import urljoin, urlparse | |
| # Conjunto para llevar un registro de las URLs visitadas | |
| urls_visitadas = set() | |
| # Función para obtener los títulos H1 a H6 de una URL | |
| def obtener_titulos(url): | |
| try: | |
| headers = { | |
| 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36' | |
| } | |
| response = requests.get(url, headers=headers) | |
| if response.status_code == 200: | |
| soup = BeautifulSoup(response.text, 'html.parser') | |
| titulos = [(titulo.name, titulo.text.strip()) for titulo in soup.find_all(['h1', 'h2', 'h3', 'h4', 'h5', 'h6'])] | |
| return titulos | |
| else: | |
| print(f"Error al obtener la página: {response.status_code}") | |
| return None | |
| except Exception as e: | |
| print(f"Error de conexión: {str(e)}") | |
| return None | |
| # Función recursiva para explorar enlaces y generar archivos CSV | |
| def explorar_y_generar_csv(url, nivel=1): | |
| global urls_visitadas | |
| # Verificar si la URL ya ha sido visitada | |
| if url in urls_visitadas: | |
| return | |
| # Agregar la URL actual al conjunto de URLs visitadas | |
| urls_visitadas.add(url) | |
| # Obtener el dominio de la URL principal | |
| domain = urlparse(url_principal).netloc | |
| # Verificar si la URL pertenece al dominio de la URL principal | |
| if domain not in urlparse(url).netloc: | |
| return | |
| # Obtener los títulos | |
| titulos = obtener_titulos(url) | |
| if titulos: | |
| # Obtener el nombre del archivo CSV | |
| nombre_archivo = titulos[0][1] if titulos else 'sin_titulos' | |
| nombre_archivo = nombre_archivo.replace(' ', '_').replace('/', '_') + '.csv' | |
| # Crear el archivo CSV con cabeceras por tipo de título | |
| with open(nombre_archivo, 'w', newline='', encoding='utf-8') as file: | |
| writer = csv.writer(file) | |
| writer.writerow(['Tipo', 'Título']) | |
| writer.writerows(titulos) | |
| print(f"Títulos guardados en {nombre_archivo}") | |
| if nivel > 0: | |
| # Explorar enlaces dentro de la página | |
| try: | |
| response = requests.get(url) | |
| if response.status_code == 200: | |
| soup = BeautifulSoup(response.text, 'html.parser') | |
| enlaces = soup.find_all('a', href=True) | |
| for enlace in enlaces: | |
| enlace_completo = urljoin(url, enlace['href']) | |
| explorar_y_generar_csv(enlace_completo, nivel - 1) | |
| except Exception as e: | |
| print(f"Error al explorar enlaces: {str(e)}") | |
| # Obtener la URL principal a través de un prompt | |
| url_principal = input("Por favor, ingresa la URL principal que deseas analizar: ") | |
| # Llamar a la función recursiva para explorar y generar CSV | |
| explorar_y_generar_csv(url_principal, nivel=2) # Cambia el nivel según la profundidad de exploración deseada |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment