questo codice di seguito indicato da questo errore:
Traceback (most recent call last):
  File "C:\Users\Utente\Desktop\Cassetto fiscale\Cassetto_con_opzioni_modifica.py", line 322, in <module>
    href = link.get_attribute('href')
  File "C:\Users\Utente\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webelement.py", line 141, in get_attribute
    self, name)
  File "C:\Users\Utente\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 636, in execute_script
    'args': converted_args})['value']
  File "C:\Users\Utente\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\Utente\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
  (Session info: chrome=109.0.5414.168)

>>> 






# Import the required modules
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import WebDriverException
from selenium.common import exceptions
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
import re

import requests

import os
import time
import json
from bs4 import BeautifulSoup
  
  
  
# Main Function
if __name__ == "__main__":

    download_folder = r'C:\Users\Utente\Desktop\Cassetto fiscale'
  
    # Enable Performance Logging of Chrome.
    desired_capabilities = DesiredCapabilities.CHROME
    desired_capabilities["goog:loggingPrefs"] = {"performance": "ALL"}
    
  
    # Create the webdriver object and pass the arguments
    options = webdriver.ChromeOptions()
    options.add_experimental_option('prefs', {
        'download.default_directory': download_folder,
        #'download.prompt_for_download': False,
        #'download.directory_upgrade': True,
       # 'plugins.plugins_disabled': ['Chrome PDF Viewer'],
       # 'profile.default_content_settings.popups': 0,
       # 'profile.content_settings.exceptions.automatic_downloads.*.setting': 1,
       # 'safebrowsing.enabled': True
        })
  
    # Chrome will start in Headless mode
    #options.add_argument('headless')
  
    # Ignores any certificate errors if there is any
    options.add_argument("--ignore-certificate-errors")
    chromedriver_path = r"C:\Users\Utente\Desktop\PYTHON\chromedrive\chromedriver.exe"
  
    # Startup the chrome webdriver with executable path and
    # pass the chrome options and desired capabilities as
    # parameters.
    driver = webdriver.Chrome(chromedriver_path, desired_capabilities=desired_capabilities, options=options)
    #driver = webdriver.Chrome(os.path.join(os.getcwd(),"Downloads","chromedriver"),options=options) 
    
    
  
    # Send a request to the website and let it load
    
    driver.get("https://portale.agenziaentrate.gov.it/PortaleWeb/home")
    cookies = driver.get_cookies()
    for cookie in cookies:
        print(cookie)
    time.sleep(10)
    
    element=driver.find_element(By.LINK_TEXT, "Credenziali").click()
    element=driver.find_element_by_id ("username-fo-ent")
    element.send_keys('')
    element=driver.find_element_by_id("pin-fo-ent")
    element.send_keys("")
    element=driver.find_element_by_id("password-fo-ent")
    element.send_keys("")
    #driver.find_element_by_id( "page-footer").click()
    element=driver.find_element(By.CSS_SELECTOR, ".px-md-5 > .btn-accedi").click()
    cookies = driver.get_cookies()

    for cookie in cookies:
       print(cookie)
       
    #Sleeps for 10 seconds
    time.sleep(10)
  
    # Gets all the logs from performance in Chrome
    logs = driver.get_log("performance")

   
  
    # Opens a writable JSON file and writes the logs in it
    with open("network_log.json", "w", encoding="utf-8") as f:
        f.write("[")
  
        # Iterates every logs and parses it using JSON
        for log in logs:
            network_log = json.loads(log["message"])["message"]
  
            # Checks if the current 'method' key has any
            # Network related value.
            if("Network.response" in network_log["method"]
                    or "Network.request" in network_log["method"]
                    or "Network.webSocket" in network_log["method"]):
  
                # Writes the network log to a JSON file by
                # converting the dictionary to a JSON string
                # using json.dumps().
                f.write(json.dumps(network_log)+",")
        f.write("{}]")
  
   
  
    # Read the JSON File and parse it using
    # json.loads() to find the urls containing images.
    json_file_path = "network_log.json"
    with open(json_file_path, "r", encoding="utf-8") as f:
        logs = json.loads(f.read())
  
    # Iterate the logs
    for log in logs:
  
        # Except block will be accessed if any of the
        # following keys are missing.
        try:
            # URL is present inside the following keys
            url = log["params"]["request"]["url"]
            if ("Network.responseReceived" in log["method"] and "requestId" in log["params"]):
                print (log["params"]["requestId"])
  
            # Checks if the extension is .png or .jpg
            
            if url.find("https://portale.agenziaentrate.gov.it/portale-rest/rs/infouser")!=-1 or url.find( "https://portale.agenziaentrate.gov.it/portale-rest/rs/notifiche/certif")!=-1 :
            #if url[len(url)-4:] != ".png" or url[len(url)-4:] != ".jpg":
                print(url, end='\n\n')
                print (log["params"]["requestId"])
                try:
                    body = driver.execute_cdp_cmd('Network.getResponseBody', {'requestId': log["params"]["requestId"]})
                    #log['body'] = body
                    print (body)
                    with open("body.json", "a", encoding="utf-8") as f:
                        f.write("{ ")
                        f.write("urlresponse:[ ")
                        f.write(json.dumps(str(body)+","))
                        f.write("],")
                        f.write("{} }")
                        f.close()
                        #__________________________________________________
                except exceptions.WebDriverException:
                    print('response.body is null')
                #log = json.loads(log["message"])["message"]
                if ("Network.responseReceived" in log["method"] and "requestId" in log["params"]):
                    for log in log["params"]["requestId"]:
                        #print(str(log))
                        try:
                            body = driver.execute_cdp_cmd('Network.getResponseBody', {'requestId': log["params"]["requestId"]})
                            #log['body'] = body
                            print (body)
                            with open("body.text", "w", encoding="utf-8") as f:
                                f.write(json.dumps(str(body)+","))
                                #__________________________________________________
                        except exceptions.WebDriverException:
                            print('response.body is null')
        except Exception as e:
            pass
    driver.get("https://cassetto.agenziaentrate.gov.it/CassHomeWeb/home")
    time.sleep(5)
    driver.get("https://cassetto.agenziaentrate.gov.it/cassfisc-web")
    time.sleep(5)
    driver.get("https://cassetto.agenziaentrate.gov.it/cassfisc-web/CassettoFiscaleServlet?Ric=VERS")
    time.sleep(5)
    driver.get("https://cassetto.agenziaentrate.gov.it/cassfisc-web/CassettoFiscaleServlet?Ric=F24&Anno=2020")
    #driver.get("https://cassetto.agenziaentrate.gov.it/cassfisc-web/CassettoFiscaleServlet?Ric=DetF24&Anno=2023&indice=0&dataDal=&dataAl=")

    html_source = driver.page_source
    # Close the browser (if needed)
    # driver.quit()
    # Parse the HTML using BeautifulSoup
    soup = BeautifulSoup(html_source, 'html.parser')
    # Find all the years within the specified section
    section_years = soup.find('section', class_='section section-anni border border-primary')
    years = []
    if section_years:
        # Find all the span elements with class 'chip-label' within the section
        year_elements = section_years.find_all('span', class_='chip-label')
        # Extract the text content (years) from the elements
        years = [element.get_text(strip=True) for element in year_elements]
        # Print the extracted years
        print(years)
    html_source = driver.page_source
    # Close the browser (if needed)
    # driver.quit()
    # Parse the HTML using BeautifulSoup
    soup = BeautifulSoup(html_source, 'html.parser')
    # Find all the years within the specified section
    section_years = soup.find('section', class_='section section-anni border border-primary')
    years_data = []
    if section_years:
        # Trovare tutti gli elementi anchor con la classe 'chip-label' all'interno della sezione
        year_elements = section_years.find_all('a', class_='btn btn-sm chip-btn')
        for element in year_elements:
            year_text = element.get_text(strip=True)
            print (year_text)
            # Saltare gli anni con "Documenti non presenti"
            if "Documenti non presenti" not in year_text:
                year_url = element['href']
                years_data.append({'year': year_text, 'url': year_url})
    # Iterare su gli anni e visitare il link specificato per ogni anno
    for data in years_data:
        year = data['year']
        print (year)
        url = data['url']#.replace("Ric=F24", "Ric=DetF24")
        driver.get(url)
        print(url)
    
    # Aggiungi la tua logica qui per estrarre informazioni dalla pagina per ogni anno
    # ...
    # Trova tutti i righe (<tr>) all'interno del corpo della tabella (<tbody>)
    rows = driver.find_elements(By.CSS_SELECTOR, "table.table-hover tbody tr")

# Andiamo a estrarre le informazioni da ogni riga
    for row in rows:
        # Ottieni tutti i dati delle colonne e mettiteli in una lista
        data = [cell.text.strip() for cell in row.find_elements(By.TAG_NAME, "th")] +     [cell.text.strip() for cell in row.find_elements(By.TAG_NAME, "td")]
        # Trova tutti i link (se esistono) nella riga
        links = [a.get_attribute('href') for a in row.find_elements(By.TAG_NAME, "a")]
    
        # Stampa i dati a schermo
        print(data + links)
        numero=data[2]
        print("Numero f24_________________ " + data[2])
    # Attendere per evitare di sovraccaricare il server con le richieste
        time.sleep(1)
        WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "table-responsive")))
        # Trova tutti i link di dettaglio nella tabella
        dettaglio_links = driver.find_elements(By.XPATH, '//th[@headers="dettaglio"]/a')
        indice=""
        protocollo=""
        # Percorre i link e salva le pagine corrispondenti
        for link in dettaglio_links:
            # Ottieni l'href del link
            href = link.get_attribute('href')
            text = link.text
            print(text)
        
     
            # Verifica se il testo contiene la parola "indice"
            if "dettaglio del versamento" in text:
                # Estrai il numero del versamento e l'indice
                versamento = text.split('n.')[0].strip()
                indice = str(text.split('n.')[1].split(' ')[0].strip())
                # Stampa il numero del versamento e l'indice
                print('Versamento:', versamento)
                print('Indice:', indice)
        
        # Ottieni il testo del protocollo corrispondente
            protocollo = link.find_element(By.XPATH, './../../td[@headers="protocollo"]').text.replace('/', '_') + '_' + indice
        
        # Costruisci il nome del file da usare per salvare la pagina HTML
            print ("download pagina html")
            file_name = f"{protocollo}.html"
            file_path = os.path.join('C:/Users/Utente/Desktop/Cassetto fiscale', file_name)
            if numero== 1:
        
            # Apri il link in una nuova finestra/tab
                driver.execute_script(f"window.open('{href}', '_blank');")
                
                #driver.execute_script(f"window.open('{href}');")
                driver.switch_to.window(driver.window_handles[0])

            # Attendi il caricamento della pagina
                WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.TAG_NAME, "html")))
            
            # Salva il contenuto della pagina
                with open(file_path, 'w', encoding='utf-8') as f:
                    f.write(driver.page_source)
                 #fa il download degli f24 singoli
            # Costruisci gli URL per i file PDF
                url_stampap = href + '&stampa=P'
                url_stampaq = href + '&stampa=Q'
                # Salva i file PDF
                for url_suffix, suffix in [(url_stampap, 'P'), (url_stampaq, 'Q')]:
                    
                    pdf_file_name = f"{protocollo}_{suffix}.pdf"
                    # Vai all'URL e inizia il download del PDF
                    #driver.get(url_suffix)
                    cookies = driver.get_cookies()
                    session = requests.Session()
                    for cookie in cookies:
                        session.cookies.set(cookie['name'], cookie['value'])
                        
                        with open(pdf_file_name, "wb") as f:
                            file_bytes = session.get(url_suffix).content
                            f.write(file_bytes)
                    driver.close()
                    driver.switch_to.window(window_handles[0])
                    driver.refresh()
                    time.sleep(5)

                    
            #controllo multi f24
            else:
                print("Più f24 insieme")
                rows = driver.find_elements(By.CSS_SELECTOR, "table.table-hover tbody tr")
                # Andiamo a estrarre le informazioni da ogni riga
                for row in rows:
                    # Ottieni tutti i dati delle colonne e mettiteli in una lista
                    data = [cell.text.strip() for cell in row.find_elements(By.TAG_NAME, "th")] +     [cell.text.strip() for cell in row.find_elements(By.TAG_NAME, "td")]
                    # Trova tutti i link (se esistono) nella riga
                    links = [a.get_attribute('href') for a in row.find_elements(By.TAG_NAME, "a")]
                    # Stampa i dati a schermo
                    print(data + links)
                    # Attendere per evitare di sovraccaricare il server con le richieste
                    time.sleep(1)
                    WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "table-responsive")))
                    # Trova tutti i link di dettaglio nella tabella
                    dettaglio_links = driver.find_elements(By.XPATH, '//th[@headers="dettaglio"]/a')
                    # Percorre i link e salva le pagine corrispondenti
                    for link in dettaglio_links:
                        # Ottieni l'href del link
                        href = link.get_attribute('href')
                        text = link.text
                        if "dettaglio del versamento" in text:
                            # Estrai il numero del versamento e l'indice
                            versamento = text.split('n.')[0].strip()
                            indice = (text.split('n.')[1].split(' ')[0].strip())
                        # Ottieni il testo del protocollo corrispondente
                        prot_org=link.find_element(By.XPATH, './../../td[@headers="protocollo"]').text
                        protocollo = link.find_element(By.XPATH, './../../td[@headers="protocollo"]').text.replace('/', '_') + '_' + indice
                        # Costruisci il nome del file da usare per salvare la pagina HTML
                        print ("multi f24 ______________________________________")
                        print ("l'indice di riferimento è "+ indice)
                        print (protocollo)
                        file_name = f"{protocollo}.html"
                        file_path = os.path.join('C:/Users/Utente/Desktop/Cassetto fiscale', file_name)
                        # Apri il link in una nuova finestra/tab
                        print (href)
                        driver.execute_script(f"window.open('{href}', '_blak');")
                        window_handles = driver.window_handles
                        driver.switch_to.window(driver.window_handles[1])
                        # Seleziona la seconda scheda (indice 1) e chiudila
                        #if len(window_handles) > 1:
                            #driver.switch_to.window(window_handles[1])
                            #driver.switch_to.window(driver.window_handles[1])
                        # Attendi il caricamento della pagina
                        WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.TAG_NAME, "html")))
                        # Salva il contenuto della pagina
                        with open(file_path, 'w', encoding='utf-8') as f:
                            f.write(driver.page_source)
                        # fa il download degli f24 multipli
                        # Costruisci gli URL per i file PDF
                        print (prot_org)
                        pattern = re.compile(r'(\d+)/(\d+)')
                        # Eseguiamo la ricerca con il pattern compilato
                        match = pattern.search(prot_org)
                        prot = match.group(1)
                        prog = match.group(2)

                        
                        hrefm="https://cassetto.agenziaentrate.gov.it/cassfisc-web/CassettoFiscaleServlet?Ric=DetF24&Anno=&indice="+ indice + "&dataDal=&dataAl=&ProtTelem=" + prot + "&ProgrTelem=" + prog
                        url_stampap = hrefm + '&stampa=P'
                        url_stampaq = href + '&stampa=Q'
                        # Salva i file PDF
                        for url_suffix, suffix in [(url_stampap, 'P'), (url_stampaq, 'Q')]:
                            pdf_file_name = f"{protocollo}_{suffix}.pdf"
                            # Vai all'URL e inizia il download del PDF
                            #driver.get(url_suffix)
                            cookies = driver.get_cookies()
                            session = requests.Session()
                            for cookie in cookies:
                                session.cookies.set(cookie['name'], cookie['value'])
                                with open(pdf_file_name, "wb") as f:
                                    file_bytes = session.get(url_suffix).content
                                    f.write(file_bytes)
                            #driver.execute_script("window.history.go(-1)")
                        
                        driver.close()
                        driver.switch_to.window(window_handles[0])
                        driver.refresh()
                        time.sleep(5)
                    
                        
                        

 
                
                

# Chiudi il browser una volta completato il processo
    
    # Chiudi la tab corrente e torna alla tab della tabella
        #driver.close()
        #driver.switch_to.window(driver.window_handles[0])

    #driver.quit()