encontrado autor y link
This commit is contained in:
136
autorsearcher.py
136
autorsearcher.py
@ -1,75 +1,93 @@
|
||||
from selenium import webdriver
|
||||
from selenium.webdriver.chrome.options import Options
|
||||
from bs4 import BeautifulSoup
|
||||
import json
|
||||
import requests
|
||||
|
||||
def get_html_without_javascript(url):
|
||||
import sys
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
def download_html_as_human(url):
|
||||
"""
|
||||
Utiliza Selenium para obtener el HTML de una página web con JavaScript desactivado.
|
||||
Descarga el HTML de una página web simulando un navegador real y usando cookies de sesión.
|
||||
"""
|
||||
# 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
|
||||
headers = {
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
|
||||
}
|
||||
|
||||
session = requests.Session()
|
||||
|
||||
# Inicializar el driver de Chrome
|
||||
driver = webdriver.Chrome(options=chrome_options)
|
||||
response = session.get(url, headers=headers)
|
||||
|
||||
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()
|
||||
if response.status_code == 200:
|
||||
return response.text
|
||||
else:
|
||||
return None
|
||||
|
||||
def get_author_from_html(html_content):
|
||||
def extract_author_from_json(json_data):
|
||||
"""
|
||||
Utiliza BeautifulSoup para extraer el autor de una página HTML.
|
||||
Extrae el autor del JSON-LD, incluso si está en una lista.
|
||||
"""
|
||||
try:
|
||||
# Analizar el HTML con BeautifulSoup
|
||||
soup = BeautifulSoup(html_content, 'html.parser')
|
||||
if isinstance(json_data, list):
|
||||
for item in json_data:
|
||||
author = extract_author_from_json(item)
|
||||
if author:
|
||||
return author
|
||||
elif isinstance(json_data, dict):
|
||||
if 'author' in json_data:
|
||||
author_data = json_data['author']
|
||||
if isinstance(author_data, list):
|
||||
for author in author_data:
|
||||
if isinstance(author, dict) and 'name' in author:
|
||||
return author['name']
|
||||
elif isinstance(author_data, dict) and 'name' in author_data:
|
||||
return author_data['name']
|
||||
return None
|
||||
|
||||
# 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):
|
||||
def get_author_from_json_ld(soup):
|
||||
"""
|
||||
Combina ambas funciones para obtener el autor desde una página con JS desactivado.
|
||||
Extrae el autor de los metadatos JSON-LD, considerando estructuras con listas y objetos.
|
||||
"""
|
||||
try:
|
||||
# Obtener el HTML sin JavaScript usando Selenium
|
||||
print("Obteniendo HTML con JavaScript desactivado...")
|
||||
html_content = get_html_without_javascript(url)
|
||||
scripts = soup.find_all('script', type='application/ld+json')
|
||||
for script in scripts:
|
||||
try:
|
||||
json_data = json.loads(script.string)
|
||||
author = extract_author_from_json(json_data)
|
||||
if author:
|
||||
return author
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
return None
|
||||
|
||||
# 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)
|
||||
def get_author_from_meta(soup):
|
||||
"""
|
||||
Extrae el autor de la etiqueta <meta> con el atributo property="nrbi:authors".
|
||||
"""
|
||||
meta_author = soup.find('meta', property='nrbi:authors')
|
||||
if meta_author and 'content' in meta_author.attrs:
|
||||
return meta_author['content']
|
||||
return None
|
||||
|
||||
# Obtener el autor desde el HTML
|
||||
print("Analizando HTML para obtener el autor...")
|
||||
author = get_author_from_html(html_content)
|
||||
def get_author_from_url(url):
|
||||
"""
|
||||
Busca el autor en los metadatos JSON-LD y en la etiqueta <meta> de una URL.
|
||||
"""
|
||||
html_content = download_html_as_human(url)
|
||||
if not html_content:
|
||||
print("error")
|
||||
return "No se pudo descargar la página."
|
||||
|
||||
soup = BeautifulSoup(html_content, 'html.parser')
|
||||
|
||||
author = get_author_from_json_ld(soup)
|
||||
if author:
|
||||
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}")
|
||||
author = get_author_from_meta(soup)
|
||||
if author:
|
||||
return author
|
||||
|
||||
return "Autor no encontrado en los metadatos."
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) > 1:
|
||||
url = sys.argv[1]
|
||||
print(get_author_from_url(url))
|
||||
else:
|
||||
print("Uso: python autorsearcher.py <URL>")
|
||||
|
Reference in New Issue
Block a user