born
This commit is contained in:
75
autorsearcher.py
Normal file
75
autorsearcher.py
Normal file
@ -0,0 +1,75 @@
|
||||
from selenium import webdriver
|
||||
from selenium.webdriver.chrome.options import Options
|
||||
from bs4 import BeautifulSoup
|
||||
import requests
|
||||
|
||||
def get_html_without_javascript(url):
|
||||
"""
|
||||
Utiliza Selenium para obtener el HTML de una página web con JavaScript desactivado.
|
||||
"""
|
||||
# Configuración de opciones de Chrome
|
||||
chrome_options = Options()
|
||||
chrome_options.add_argument("--disable-dev-shm-usage") # Usa memoria compartida si no hay suficiente RAM
|
||||
chrome_options.add_argument("--no-sandbox") # Desactiva el sandboxing (problema común en entornos sin root)
|
||||
chrome_options.add_argument("--disable-extensions") # Desactiva extensiones del navegador
|
||||
chrome_options.add_argument("--remote-debugging-port=9222") # Debugging remoto
|
||||
chrome_options.add_argument("--headless=new") # Nueva implementación de headless
|
||||
|
||||
|
||||
# Inicializar el driver de Chrome
|
||||
driver = webdriver.Chrome(options=chrome_options)
|
||||
|
||||
try:
|
||||
# Accede al sitio web
|
||||
driver.get(url)
|
||||
# Obtener el contenido de la página
|
||||
html_content = driver.page_source
|
||||
return html_content
|
||||
finally:
|
||||
# Cierra el navegador
|
||||
driver.quit()
|
||||
|
||||
def get_author_from_html(html_content):
|
||||
"""
|
||||
Utiliza BeautifulSoup para extraer el autor de una página HTML.
|
||||
"""
|
||||
try:
|
||||
# Analizar el HTML con BeautifulSoup
|
||||
soup = BeautifulSoup(html_content, 'html.parser')
|
||||
|
||||
# Buscar la meta tag con name="autor"
|
||||
author_meta = soup.find('meta', attrs={'name': 'autor'})
|
||||
|
||||
# Si existe, devolver el contenido del atributo "content"
|
||||
if author_meta and 'content' in author_meta.attrs:
|
||||
return author_meta['content']
|
||||
else:
|
||||
return "No se encontró el autor en la meta etiqueta."
|
||||
except Exception as e:
|
||||
return f"Error al analizar el HTML: {e}"
|
||||
|
||||
# Función principal
|
||||
def main(url):
|
||||
"""
|
||||
Combina ambas funciones para obtener el autor desde una página con JS desactivado.
|
||||
"""
|
||||
try:
|
||||
# Obtener el HTML sin JavaScript usando Selenium
|
||||
print("Obteniendo HTML con JavaScript desactivado...")
|
||||
html_content = get_html_without_javascript(url)
|
||||
|
||||
# Guardar el HTML en un archivo local (opcional)
|
||||
with open("pagina_web_sin_js.html", "w", encoding="utf-8") as file:
|
||||
file.write(html_content)
|
||||
|
||||
# Obtener el autor desde el HTML
|
||||
print("Analizando HTML para obtener el autor...")
|
||||
author = get_author_from_html(html_content)
|
||||
return author
|
||||
except Exception as e:
|
||||
return f"Error general: {e}"
|
||||
|
||||
# Ejemplo de uso
|
||||
url = "https://www.abc.es/internacional/trump-presidente-vez-era-dorada-empieza-momento-20250120202851-nt.html"
|
||||
author = main(url)
|
||||
print(f"El autor es: {author}")
|
1
keywords.txt
Normal file
1
keywords.txt
Normal file
@ -0,0 +1 @@
|
||||
Real Madrid
|
0
news_data.json
Normal file
0
news_data.json
Normal file
81
webscrapper.py
Normal file
81
webscrapper.py
Normal file
@ -0,0 +1,81 @@
|
||||
import requests
|
||||
from bs4 import BeautifulSoup
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
|
||||
HEADERS = {
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
|
||||
}
|
||||
|
||||
def search_news(query):
|
||||
"""
|
||||
Busca noticias relacionadas con una palabra clave en Google News.
|
||||
"""
|
||||
base_url = f"https://news.google.com/rss/search?q={query.replace(' ', '+')}&hl=es&gl=ES&ceid=ES%3Aes"
|
||||
response = requests.get(base_url, headers=HEADERS)
|
||||
|
||||
if response.status_code != 200:
|
||||
print(f"Error al acceder a la página para la consulta '{query}': {response.status_code}")
|
||||
return []
|
||||
|
||||
# Analizar el RSS como XML
|
||||
soup = BeautifulSoup(response.content, 'xml') # Cambié 'html.parser' por 'xml'
|
||||
articles = soup.find_all("item") # Los artículos están dentro de etiquetas <item> en RSS
|
||||
news_list = []
|
||||
|
||||
for article in articles[:10]: # Limitar a las 10 primeras noticias
|
||||
try:
|
||||
title = article.title.get_text(strip=True)
|
||||
content = article.description.get_text(strip=True) if article.description else "Sin descripción"
|
||||
link = article.link.get_text(strip=True)
|
||||
source_info = article.source.get_text(strip=True) if article.source else "Desconocido"
|
||||
date = article.pubDate.get_text(strip=True) if article.pubDate else "Fecha no disponible"
|
||||
|
||||
news_item = {
|
||||
"title": title,
|
||||
"content": content,
|
||||
"author": "Desconocido", # Autor no disponible en esta consulta
|
||||
"newspaper": source_info,
|
||||
"date": date,
|
||||
"link": link
|
||||
}
|
||||
|
||||
news_list.append(news_item)
|
||||
except Exception as e:
|
||||
print(f"Error al procesar un artículo para '{query}': {e}")
|
||||
|
||||
return news_list
|
||||
|
||||
def search_from_keywords_file():
|
||||
"""
|
||||
Lee palabras clave del archivo 'keywords.txt' y realiza búsquedas para cada una.
|
||||
"""
|
||||
all_news = [] # Lista para almacenar todas las noticias recolectadas
|
||||
|
||||
try:
|
||||
with open("keywords.txt", "r", encoding="utf-8") as file:
|
||||
keywords = file.readlines()
|
||||
|
||||
# Eliminar posibles saltos de línea y espacios extra
|
||||
keywords = [keyword.strip() for keyword in keywords]
|
||||
|
||||
for keyword in keywords:
|
||||
print(f"\nBuscando noticias sobre: {keyword}")
|
||||
news_list = search_news(keyword)
|
||||
all_news.extend(news_list) # Añadir las noticias encontradas para cada palabra clave
|
||||
time.sleep(2) # Pausa para evitar bloqueos por demasiadas solicitudes en poco tiempo
|
||||
|
||||
# Guardar todas las noticias en un archivo JSON
|
||||
with open('news_data.json', 'w', encoding='utf-8') as json_file:
|
||||
json.dump(all_news, json_file, ensure_ascii=False, indent=4)
|
||||
print("\nTodas las noticias han sido guardadas en 'news_data.json'.")
|
||||
|
||||
except FileNotFoundError:
|
||||
print("No se encontró el archivo 'keywords.txt'.")
|
||||
except Exception as e:
|
||||
print(f"Error al leer el archivo 'keywords.txt': {e}")
|
||||
|
||||
# Ejecutar la búsqueda desde el archivo
|
||||
search_from_keywords_file()
|
||||
|
Reference in New Issue
Block a user