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

Edge无头模式下Python网页文件下载失效问题

Edge无头模式下无法下载文件的解决方法

这问题是因为Edge无头模式默认不会自动处理下载操作,得手动配置浏览器参数和下载偏好才能解决,具体修改如下:

关键配置步骤

  • 导入EdgeOptions类来设置浏览器参数
  • 使用新版无头模式参数--headless=new(旧版无头模式兼容性差,容易出问题)
  • 指定下载路径,禁用下载弹窗,让文件自动保存到目标目录

修改后的完整代码

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.webdriver.edge.options import EdgeOptions

# 配置Edge浏览器选项
options = EdgeOptions()
# 启用新版无头模式
options.add_argument("--headless=new")
# 设置下载路径(替换成你自己的目录路径)
download_path = "C:/Your/Download/Path"
prefs = {
    "download.default_directory": download_path,
    "download.prompt_for_download": False,
    "download.directory_upgrade": True,
    "safebrowsing.enabled": True
}
options.add_experimental_option("prefs", prefs)

# 初始化带配置的浏览器
driver = webdriver.Edge(options=options)
driver.get("URL")

id_box = driver.find_element(By.ID,"...")
pw_box = driver.find_element(By.ID,"...")
id_box.send_keys("...")
pw_box.send_keys("...")
log_in = driver.find_element(By.ID,"...")
log_in.click()

time.sleep(0.1) # 这里建议换成显式等待,比固定等待更稳定

drop_period = Select(driver.find_element(By.ID,"..."))
drop_period.select_by_index(1)
drop_consul = Select(driver.find_element(By.ID,"..."))
drop_consul.select_by_visible_text("...")
drop_client = Select(driver.find_element(By.ID,"..."))
drop_client.select_by_index(1)

# 现在点击下载应该能正常工作了
driver.find_element(By.XPATH, "...").click()
driver.find_element(By.XPATH, "...").click()

# 记得最后关闭浏览器
driver.quit()

额外提示

  • 把代码里的download_path替换成你实际要保存文件的目录,路径要用正斜杠或者双反斜杠
  • 原来的time.sleep(0.1)可以换成显式等待,避免固定等待时间导致的不稳定,示例:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 替换time.sleep(0.1)
WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.ID, "你的下拉框ID"))
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 21:05:19