Calificación:
  • 0 voto(s) - 0 Media
  • 1
  • 2
  • 3
  • 4
  • 5
Duda python para descargar pdf
#1
Hola, 
Estoy programando un pequeño código que va entrando en diferentes links y debe navegar por una página y descargar los pdfs que encuentre, pero por algún motivo no los detecta, y por tanto, no los descarga. Les dejo el código resumido para un caso a ver si pueden ayudarme:
import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
import os
import requests
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
# Crear una carpeta per guardar els documents descarregats
carpeta_descargas = "Documents_Descarregats_Ajuntament"
if not os.path.exists(carpeta_descargas):
    os.makedirs(carpeta_descargas)
# Configura el WebDriver.
driver = webdriver.Chrome()  # Assegura't que ChromeDriver està instal·lat i configurat
try:
    # 1. Obre Google
    driver.get("https://contractaciopublica.cat/ca/detall-publicacio/3a992746-70c0-48f7-ae49-2377ed4cd3c9/200152387")
    # 2. Accepta cookies (si cal)
    try:
        accept_cookies_button = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH, "//button[contains(text(),'Accepta')]")))
        accept_cookies_button.click()
    except Exception:
        print("No s'ha trobat el botó de cookies. Continuant...")
    # 3. Cerca l'enllaç 'Anunci de licitació
    gmail_link = driver.find_element(By.LINK_TEXT, "Anunci de licitació")
    # 4. Fes clic a 'Anunci de licitació'
    gmail_link.click()
    # Opcional: Espera per veure el resultat
    time.sleep(5)
    # Desplaçar-se cap al final de la pàgina
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    time.sleep(5)  # Dona temps a carregar el contingut
    pdf_links = WebDriverWait(driver, 10).until(
    EC.presence_of_all_elements_located((By.XPATH, "//a[contains(@href, '.pdf')]")))
    for pdf_link in pdf_links:
        pdf_url = pdf_link.get_attribute("href")
        pdf_text = pdf_link.text.strip().lower()
          # Download the PDF
        try:
            response = requests.get(pdf_url)
            response.raise_for_status()  # This will raise an exception for HTTP errors
            filename = os.path.join(carpeta_descargas, pdf_url.split('/')[-1])
            with open(filename, 'wb') as f:
                f.write(response.content)
                print(f"PDF descarregat correctament com {filename}")
        except requests.exceptions.RequestException as e:
            print(f"Error descarregant el PDF: {e}")
        time.sleep(5)
finally:
    # Tanca el navegador
    driver.quit()
Responder
#2
Tuvo que hacer unos cambios y trucos para que funcionara.

Suerte.


Código:
import pandas as pd
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
import time
import os
import requests
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

def multiple_tries(element, maximum_try, sleep_time):
    done = False
    tries = 0
    while not done or tries > maximum_try:
        try:
            print(f"===> Downloading {element.text}")
            element.click()
            done = True
        except Exception as e:
            # print(f"Exception: {e}")
            print("Exception on click. Retryng ....")
            tries = tries + 1
        time.sleep(sleep_time)
    if done:
        print(f"+++++ Succefully donwloaded {element.text}")
    else:
        print(f"----- Failed donwload {element.text}")


# Crear una carpeta per guardar els documents descarregats
carpeta_descargas = "Documents_Descarregats_Ajuntament"

if not os.path.exists(carpeta_descargas):
    os.makedirs(carpeta_descargas)

# Configura el WebDriver.
chrome_options = Options()
prefs = {'download.default_directory': os.path.abspath(carpeta_descargas)}
chrome_options.add_experimental_option('prefs', prefs)
driver = webdriver.Chrome(options=chrome_options) # Assegura't que ChromeDriver està instal·lat i configurat

try:
    # 1. Obre Google
    driver.get("https://contractaciopublica.cat/ca/detall-publicacio/3a992746-70c0-48f7-ae49-2377ed4cd3c9/200152387")
    # 2. Accepta cookies (si cal)
    try:
        accept_cookies_button = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH, "//button[contains(text(),'Accepta')]")))
        accept_cookies_button.click()
    except Exception:
        print("No s'ha trobat el botó de cookies. Continuant...")
   
    # 3. Cerca l'enllaç 'Anunci de licitació
    gmail_link = driver.find_element(By.LINK_TEXT, "Anunci de licitació")
    # 4. Fes clic a 'Anunci de licitació'
    gmail_link.click()
    # Opcional: Espera per veure el resultat
    time.sleep(5)

    # Desplaçar-se cap al final de la pàgina
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    time.sleep(5)  # Dona temps a carregar el contingut
   
    pdf_links = driver.find_elements(By.XPATH, '//*[@id="documentacio-panel"]/div/app-anunci-licitacio-documentacio/div/*/div/div[2]/div/button')
   
    for pdf_link in pdf_links:
        try:
            multiple_tries(element=pdf_link, maximum_try=10, sleep_time=5)
        except Exception as e:
            print(f"Error descarregant el PDF: {e}")

finally:
    # Tanca el navegador
    driver.quit()
Responder


Salto de foro:


Usuarios navegando en este tema: 1 invitado(s)