You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Selenium和Python点击无URL按钮实现文件下载

解决Selenium点击下载按钮无响应的问题

核心问题排查与修复步骤

  • 等待元素加载完成:页面未完全加载时直接查找元素,会导致定位失败或点击无效,用显式等待替代直接查找
  • 配置Chrome下载参数:指定下载目录并关闭下载弹窗,避免交互干扰
  • 优化元素定位精度:若页面存在多个同class的按钮,需补充定位条件
  • 处理iframe嵌套:如果按钮在iframe内,需先切换到对应iframe再操作

修复后的代码示例

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options

# 配置Chrome下载选项
download_dir = 'C:/Users/ASUS/Documents/data'
chrome_options = Options()
chrome_options.add_experimental_option("prefs", {
    "download.default_directory": download_dir,
    "download.prompt_for_download": False,
    "download.directory_upgrade": True,
    "safebrowsing.enabled": True
})

# 初始化驱动(推荐用webdriver_manager自动管理驱动版本)
driver = webdriver.Chrome(options=chrome_options)
driver.get("http://www.ins.tn/statistiques/90#")

try:
    # 显式等待按钮可点击,最长等待10秒
    button = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.CLASS_NAME, "btnexport"))
    )
    # 用JS点击规避元素遮挡问题
    driver.execute_script("arguments[0].click();", button)
finally:
    # 可根据需求选择是否关闭驱动,建议等待下载完成后再执行quit()
    # driver.quit()
    pass

额外排查方向

  • 若页面存在多个btnexport按钮,用find_elements(By.CLASS_NAME, "btnexport")获取所有匹配元素,再通过按钮文本、父元素属性等筛选目标按钮
  • 检查按钮是否在<iframe>标签内:打开浏览器开发者工具,若按钮属于iframe嵌套内容,需先执行driver.switch_to.frame(iframe_element)切换上下文
  • 确认网站是否有反爬限制(如登录验证、人机校验),需先完成对应验证步骤再执行下载操作

内容的提问来源于stack exchange,提问作者Monica

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 15:39:14