无论如何,我可以使用selenium获取最后下载的文件。目前我正在使用selenium下载Excel文件,我需要获取该文件并阅读它。阅读部分已被覆盖,但我需要下载的文件路径和文件名才能阅读。到目前为止,我还没有发现任何有用的东西。我主要是寻找一个谷歌Chrome解决方案,但firefox也可以。
提前致谢
答案 0 :(得分:1)
您可以使用配置文件将下载内容保存到修复位置。检查这些讨论:
Downloading file to specified location with Selenium and python
Access to file download dialog in Firefox
如你所说,你已经覆盖了阅读部分。你可以从那个固定的位置阅读它。
答案 1 :(得分:1)
以下是有助于解决上述问题的代码段:
**Changes in driver file:**
protected File downloadsDir = new File("");
if (browser.equalsIgnoreCase("firefox"))
{
downloadsDir = new File(System.getProperty("user.dir") + File.separatorChar + "downloads");
if (!downloadsDir.exists())
{
boolean ddCreated = downloadsDir.mkdir();
if (!ddCreated) {
System.exit(1);
}
}
}
/*Firefox browser profile*/
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.setPreference("browser.download.folderList", 2);
firefoxProfile.setPreference("browser.download.manager.showWhenStarting", false);
firefoxProfile.setPreference("browser.download.dir", downloadsDir.getAbsolutePath());
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk", "text/plain,application/octet-stream");
**Empty the download directory[Can be implemented as @BeforeClass]:**
public void emptyDownloadsDir()
{
// Verify downloads dir is empty, if not remove all files.
File[] downloadDirFiles = downloadsDir.listFiles();
if (downloadDirFiles != null) {
for (File f : downloadDirFiles) {
if (f.exists()) {
boolean deleted = FileUtility.delete(f);
assertTrue(deleted, "Files are not deleted from system local directory" + downloadsDir + ", skipping the download tests.");
}
}
}
}
**Check the Latest downloaded file:**
/*Test file*/
protected static String EXCEL_FILE_NAME= Test_Excel_File.xls;
protected static int WAIT_IN_SECONDS_DOWNLOAD = 60;
// Wait for File download.
int counter = 0;
while (counter++ < WAIT_IN_SECONDS_DOWNLOAD && (downloadsDir.listFiles().length != 1 || downloadsDir.listFiles()[0].getName().matches(EXCEL_FILE_NAME))) {
this.wait(2);
}
// Verify the downloaded File by comparing name.
File[] downloadDirFiles = downloadsDir.listFiles();
String actualName = null;
for (File file : downloadDirFiles) {
actualName = file.getName();
if (actualName.equals(EXCEL_FILE_NAME)) {
break;
}
}
assertEquals(actualName, EXCEL_FILE_NAME, "Last Downloaded File name does not matches.");
答案 2 :(得分:0)
import os
import glob
home = os.path.expanduser("~")
downloadspath=os.path.join(home, "Downloads")
list_of_files = glob.glob(downloadspath+"\*.pptx") # * means all if need specific format then *.csv
latest_file = max(list_of_files, key=os.path.getctime)
简化的解决方案,可获取“下载”文件夹中最后一个文件的路径。上面的代码将获取Downlodas中最新.pptx文件的路径。根据需要更改扩展名。否则,您可以选择不指定扩展名