questo codice di seguito indicato da questo errore: Traceback (most recent call last):…
- User
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 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") - Assistant