Selenium在下载时提供文件名 [英] Selenium give file name when downloading

查看:3416
本文介绍了Selenium在下载时提供文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用硒脚本,我正在尝试下载一个Excel文件并给它一个特定的名称。这是我的代码:

I am working with a selenium script where I am trying to download a Excel file and give it a specific name. This is my code:

有没有可以给文件下载一个特定的名字?

Is there anyway that I can give the file being downloaded a specific name ?

代码:

#!/usr/bin/python
from selenium import webdriver
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile

profile = FirefoxProfile()
profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/plain, application/vnd.ms-excel, text/csv, text/comma-separated-values, application/octet-stream")
profile.set_preference("browser.download.dir", "C:\\Downloads" )
browser = webdriver.Firefox(firefox_profile=profile)

browser.get('https://test.com/')
browser.find_element_by_partial_link_text("Excel").click() # Download file


推荐答案

您无法通过selenium指定下载文件的名称。但是,您可以下载文件,在下载的文件夹中找到最新的文件,并根据需要重新命名。

You cannot specify name of download file through selenium. However, you can download the file, find the latest file in the downloaded folder, and rename as you want.

注意:从Google搜索中借用的方法可能会有错误。但是你得到这个想法。

Note: borrowed methods from google searches may have errors. but you get the idea.

import os
import shutil

filename = max([f for f in os.listdir('c:\downloads')], key=os.path.getctime)
shutil.move(os.path.join(dirpath,filename),newfilename)

这篇关于Selenium在下载时提供文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆