使用Python从指定INAIL统计页面下载CSV数据失败,仅获HTML文件求助
问题分析与解决方案
你的代码主要有两个核心问题导致下载到HTML而非CSV:
1. 重复使用相同的XPATH选择器
点击"Dati"和"CSV"时用了完全一样的XPATH://*[@id="popupMenuItem"]/table/tbody/tr/td[2]。实际上,点击"Esporta"后弹出的是第一级菜单,选择"Dati"后会弹出第二级子菜单,这两个菜单的元素路径不可能完全相同,重复选择会导致你可能只是重复点击了同一个元素,而非选择CSV选项。
2. 依赖动态生成的元素ID
原代码中定位"Esporta"按钮的XPATH包含了动态生成的ID(比如uiqor2i5pr25913u、cadc28dh9ejqrg6oLinks),这类ID每次页面加载都会变化,不仅可能导致元素定位失败,也不利于代码稳定性。
修正后的代码
下面是调整后的代码,改用文本定位和稳定的元素属性来定位按钮,同时补充了CSV下载的MIME类型设置:
from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import time # Setup Chrome options chrome_options = Options() chrome_options.add_experimental_option("prefs", { "download.default_directory": r"C:\Users\ColameoMarcello\Downloads", "download.prompt_for_download": False, "download.directory_upgrade": True, # 明确指定CSV的MIME类型,避免浏览器将其识别为HTML "plugins.always_open_pdf_externally": True, "mime_types": { "text/csv": "application/octet-stream" } }) # Initialize the WebDriver driver = webdriver.Chrome(options=chrome_options) try: # Navigate to the page driver.get("https://bancadatistatisticaoas.inail.it/analytics/saw.dll?Portal&PortalPath=%2Fshared%2FBDS%2F_portal%2FINF_Denunciati_totale_gestioni") # 等待页面加载完成,用稳定的方式定位Esporta按钮(按文本+链接属性) esporta_button = WebDriverWait(driver, 20).until( EC.element_to_be_clickable((By.XPATH, '//a[contains(text(), "Esporta")]')) ) esporta_button.click() # 等待第一级菜单的"Dati"选项出现并点击(按文本定位) dati_button = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.XPATH, '//td[contains(text(), "Dati")]')) ) dati_button.click() # 等待第二级子菜单的"CSV"选项出现并点击(按文本定位) csv_button = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.XPATH, '//td[contains(text(), "CSV")]')) ) csv_button.click() # 等待下载完成(可根据文件大小调整时间,或用更严谨的文件监听方式) time.sleep(15) finally: # Clean up by closing the browser driver.quit()
额外优化建议
- 避免使用
time.sleep(),可以通过监听下载目录中的文件状态(比如检查是否存在后缀为.crdownload的临时文件,直到该文件消失)来判断下载是否完成,这样更可靠。 - 如果页面需要登录或有会话验证,确保你的WebDriver实例保留了正确的会话状态。
内容的提问来源于stack exchange,提问作者Marcello
相关产品推荐
相关产品推荐

