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

爬虫脚本优化:指定路径存储文件并按执行时间命名

解决方法

要实现指定路径存储导出文件并添加时间戳后缀,需要分三步处理:配置Chrome下载路径、等待下载完成、重命名文件添加时间戳。以下是修改后的完整代码:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import os
import time
from datetime import datetime

# 指定下载目录
download_dir = r"C:\Users\ASUS\Documents\data"
# 确保目录存在,不存在则创建
os.makedirs(download_dir, exist_ok=True)

# 配置Chrome浏览器下载参数
options = webdriver.ChromeOptions()
prefs = {
    "download.default_directory": download_dir,
    "download.prompt_for_download": False,  # 不弹出下载确认框
    "download.directory_upgrade": True,
    "safebrowsing.enabled": True  # 允许下载安全文件
}
options.add_experimental_option("prefs", prefs)

# 初始化浏览器
driver = webdriver.Chrome(executable_path="C:/chrome/chromedriver.exe", options=options)
driver.get("http://www.ins.tn/statistiques/90#")

# 点击导出Excel按钮
WebDriverWait(driver, 20).until(
    EC.element_to_be_clickable((By.XPATH, "//div[@class='export']//a[@class='btnexport  ' and starts-with(@id, 'btnExporttoExcel')]"))
).click()

# 等待下载完成的函数
def wait_for_download(download_dir, timeout=30):
    end_time = time.time() + timeout
    while time.time() < end_time:
        # 遍历目录,排除Chrome临时下载文件(.crdownload后缀)
        for filename in os.listdir(download_dir):
            file_path = os.path.join(download_dir, filename)
            if os.path.isfile(file_path) and not filename.endswith(".crdownload"):
                return file_path
        time.sleep(1)
    raise TimeoutError("文件下载超时")

# 等待下载完成并获取文件路径
downloaded_file = wait_for_download(download_dir)

# 生成时间戳后缀(格式:年-月-日_时-分-秒,可自定义)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")

# 重命名文件,添加时间戳
file_name, file_ext = os.path.splitext(os.path.basename(downloaded_file))
new_file_name = f"{file_name}_{timestamp}{file_ext}"
new_file_path = os.path.join(download_dir, new_file_name)
os.rename(downloaded_file, new_file_path)

# 关闭浏览器
driver.quit()

关键部分说明

  • 配置下载路径:通过ChromeOptions的prefs设置默认下载目录,同时关闭下载弹窗,确保文件直接下载到指定路径。
  • 等待下载完成:通过循环检测下载目录,排除Chrome的临时下载文件(.crdownload后缀),确保文件完全下载后再进行后续操作。
  • 添加时间戳:使用datetime模块生成当前时间的字符串格式,作为文件名后缀,避免文件覆盖。
  • 目录创建:用os.makedirs确保指定的下载目录存在,防止因目录不存在导致下载失败。

内容的提问来源于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 17:48:19