【问题标题】:Selenium: Opening a Downloaded File in JavaSelenium:在 Java 中打开下载的文件
【发布时间】:2017-07-07 01:03:04
【问题描述】:
我需要使用 selenium 打开并读取下载的文件,但我不太确定该怎么做。我看到建议在选定位置下载文件的答案。我的代码真的需要从将文件下载到选定位置开始还是可以在下载后直接开始?
打开文件后,我还必须阅读它。谁能给我一个关于如何做到这一点的想法?谢谢!
【问题讨论】:
-
-
欢迎来到 Stack Overflow!请参阅:How do I do X? SO 的期望是,提出问题的用户不仅会进行研究以回答他们自己的问题,还会分享该研究、代码尝试和结果。这表明您已经花时间尝试帮助自己,它使我们免于重复明显的答案,最重要的是它可以帮助您获得更具体和相关的答案!另见:How to Ask
标签:
java
file
selenium
download
【解决方案1】:
您可以使用以下代码读取文件:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFileExample1 {
private static final String FILENAME = "E:\\test\\filename.txt";
public static void main(String[] args) {
BufferedReader br = null;
FileReader fr = null;
try {
fr = new FileReader(FILENAME);
br = new BufferedReader(fr);
String sCurrentLine;
br = new BufferedReader(new FileReader(FILENAME));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
希望对你有所帮助。
【解决方案2】:
您可以使用这行代码来处理从 chrome 和 forefox 浏览器下载文件。
public static File waitForDownloadToComplete(File downloadPath, String fileName) throws Exception {
boolean isFileFound = false;
int waitCounter = 0;
while (!isFileFound) {
logger.info("Waiting For Download To Complete....");
for (File tempFile : downloadPath.listFiles()) {
if (tempFile.getName().contains(fileName)) {
String tempEx = FilenameUtils.getExtension(tempFile.getName());
// crdownload - For Chrome, part - For Firefox
if (tempEx.equalsIgnoreCase("crdownload") || tempEx.equalsIgnoreCase("part")) {
Thread.sleep(1000);
} else {
isFileFound = true;
logger.info("Download To Completed....");
return tempFile;
}
}
}
Thread.sleep(1000);
waitCounter++;
if (waitCounter > 25) {
isFileFound = true;
}
}
throw new Exception("File Not Downloaded");
}
}