Lavanguardia parser, por los LOLs
En 30 minuts he pogut programar un petit scrapper amb python per llegir el contingut de lavanguardia sense passar pel paywall.
Of course, chatgepetto mediante.
Aquí el codi, posa qualsevol noticia i treu el text en raw, es pot millorar però vaja, ja us feu la idea.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
import time
def scrap_content(url):
# Configuración de Selenium
chrome_path = "./chromedriver" # Ruta al ejecutable de ChromeDriver
chrome_options = Options()
chrome_options.binary_location = "/usr/bin/google-chrome-stable"
chrome_options.add_argument(" --no-sandbox")
# Iniciar el navegador Chrome controlado por Selenium
service = Service(chrome_path)
driver = webdriver.Chrome(service=service, options=chrome_options)
#url = "https://www.lavanguardia.com/ciencia/20240327/9583611/neurocientificos-descifran-como-actua-psicoterapia-cerebro.html"
driver.get(url)
# Hacer scroll hasta el final de la página
last_height = driver.execute_script("return document.body.scrollHeight")
while True:
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(2) # Esperar a que cargue el contenido
new_height = driver.execute_script("return document.body.scrollHeight")
if new_height == last_height:
break
last_height = new_height
# Obtener el HTML de la página después de hacer scroll
html = driver.page_source
# Cerrar el navegador controlado por Selenium
driver.quit()
# Analizar el HTML con BeautifulSoup y extraer el texto dentro de las etiquetas y
soup = BeautifulSoup(html, "html.parser")
content_tags = soup.find_all(lambda tag: tag.name in ['div', 'span'])
for tag in content_tags:
text = tag.get_text().strip()
if text and len(text) >= 10:
print(text)
# URL de entrada
url = input("Por favor, introduce la URL: ")
# Llamar a la función para hacer scraping
scrap_content(url)

No hay comentarios:
Publicar un comentario