Selenium无报错但文件未下载至本地问题求助
问题分析与解决方法
1. 元素定位错误
你当前点击的是下载按钮内部的<i>图标元素,这个元素通常没有绑定下载触发的点击事件,真正的交互逻辑在它的父级<a>标签上。修改CSS选择器,直接定位<a>标签:
element = driver.find_element(By.CSS_SELECTOR, "div#main-content-column a.toolbar-button.download.ng-isolate-scope")
2. 无头模式缺少下载配置
Chrome无头模式默认不会自动保存文件,必须手动配置下载路径并禁用弹窗,否则文件可能被存到临时目录或无法保存。更新ChromeOptions配置:
chrome_options = Options() chrome_options.add_argument("--headless=new") # 新版无头模式兼容性更好 chrome_options.add_argument("--disable-gpu") # 替换成你自己的本地下载路径 download_path = "/Users/hudso/Downloads" chrome_options.add_experimental_option("prefs", { "download.default_directory": download_path, "download.prompt_for_download": False, "download.directory_upgrade": True, "safebrowsing.enabled": True })
3. ChromeDriver路径错误
你用的是Mac系统,但路径里的chromedriver.exe是Windows版本的,Mac的ChromeDriver没有.exe后缀,同时建议用新版Selenium的Service类初始化驱动:
DRIVER_PATH = '/Users/hudso/OneDrive/Documents/UST course/chromedriver' service = Service(DRIVER_PATH) driver = webdriver.Chrome(service=service, options=chrome_options)
4. 等待下载完成再关闭浏览器
time.sleep(5)不可靠,文件可能还没下载完成就被强制关闭浏览器。可以写个简单的等待函数,确认文件下载完成:
import os def wait_for_download(download_path, timeout=30): end_time = time.time() + timeout while time.time() < end_time: # 排除Chrome的临时下载文件(.crdownload后缀) files = [f for f in os.listdir(download_path) if not f.endswith('.crdownload')] if files: return max([os.path.join(download_path, f) for f in files], key=os.path.getctime) time.sleep(1) return None # 点击下载后调用等待函数 element.click() wait_for_download(download_path)
完整修复后的代码
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from selenium.webdriver.chrome.options import Options import time import os # 配置Chrome选项 chrome_options = Options() chrome_options.add_argument("--headless=new") chrome_options.add_argument("--disable-gpu") download_path = "/Users/hudso/Downloads" chrome_options.add_experimental_option("prefs", { "download.default_directory": download_path, "download.prompt_for_download": False, "download.directory_upgrade": True, "safebrowsing.enabled": True }) # 初始化驱动 DRIVER_PATH = '/Users/hudso/OneDrive/Documents/UST course/chromedriver' service = Service(DRIVER_PATH) driver = webdriver.Chrome(service=service, options=chrome_options) # 访问目标页面 driver.get("https://www.barchart.com/etfs-funds/quotes/QQQ/options?expiration=2023-06-08-w") # 定位下载按钮 element = driver.find_element(By.CSS_SELECTOR, "div#main-content-column a.toolbar-button.download.ng-isolate-scope") # 等待页面加载稳定 time.sleep(3) # 触发下载 element.click() # 等待下载完成 def wait_for_download(download_path, timeout=30): end_time = time.time() + timeout while time.time() < end_time: files = [f for f in os.listdir(download_path) if not f.endswith('.crdownload')] if files: print(f"文件已下载:{max([os.path.join(download_path, f) for f in files], key=os.path.getctime)}") return time.sleep(1) print("下载超时") wait_for_download(download_path) # 关闭浏览器 driver.quit()
内容的提问来源于stack exchange,提问作者h0204663
相关产品推荐
相关产品推荐

