【发布时间】:2012-06-03 19:30:18
【问题描述】:
我正在使用 Selenium 2.21.0 和 Java 6。如何使用 Selenium WebDriver API 下载网页上的文件?也就是说,有一个链接会导致 Excel 文件的下载开始。我想知道如何启动该下载,确定何时完成,然后确定文件在我的本地系统上的下载位置。
【问题讨论】:
-
This 可能会有所帮助。
我正在使用 Selenium 2.21.0 和 Java 6。如何使用 Selenium WebDriver API 下载网页上的文件?也就是说,有一个链接会导致 Excel 文件的下载开始。我想知道如何启动该下载,确定何时完成,然后确定文件在我的本地系统上的下载位置。
【问题讨论】:
点击任何链接下载文件后,它取决于浏览器的行为,例如 Chrome 行为:默认情况下,只要用户单击任何文件的链接,它就会开始下载文件。 IE 行为:IE 在窗口底部显示一个栏,并显示保存或取消文件下载的选项。 FireFox 行为:这将显示一个对话框窗口并显示保存或取消文件下载的选项。 所以这可以在 FireFox Profile 的帮助下实现。 并且在下载任何文件之前,您必须将文件的 MIME 类型传递给 FireFox 配置文件。 一些常用的 MIME 类型是: 文本文件 (.txt) – 文本/纯文本 PDF 文件 (.pdf) – 应用程序/pdf CSV 文件 (.csv) – 文本/csv MS Excel 文件 (.xlsx) – application/vnd.openxmlformats-officedocument.spreadsheetml.sheet MS word 文件 (.docx) – application/vnd.openxmlformats-officedocument.wordprocessingml.document
代码如下:
import org.openqa.selenium.By;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
public class DownloadFiles {
public static void main(String[] args) throws InterruptedException {
//Create FireFox Profile object
FirefoxProfile p = new FirefoxProfile();
//Set Location to store files after downloading.
profile.setPreference("browser.download.folderList", 2);
//Set preference not to file confirmation dialogue
profile.setPreference("browser.helperApps.neverAsk.saveToDisk",
"application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet");
// Specify the local system path where to download
p.setPreference("browser.download.dir", "D:\\downloads");
// Pass Profile parameters in Firefox browser
FirefoxDriver driver = new FirefoxDriver(profile);
// Open APP to download application
driver.get("http://url");
// Click to download
driver.findElement(By.xpath("//html[@attribute='value']")).click();
Thread.sleep(5000);
driver.close();
希望它能解决您的疑问。编码愉快。
【讨论】:
我特别关注 Firefox 浏览器,当访问者点击任何下载链接时,您可以使用下载选项附带弹出选项的地方。它显示了两个按钮和两个单选按钮,让我们可以选择保存并直接打开文件,而无需事后下载,如果我们发现文件有用,我们可以通过 Firefox 浏览器上方工具栏上的下载图标明确下载。 所以你可以执行以下步骤
1) 点击下载链接
WebDriver driver = new FirefoxDriver();
driver.findElement(By.linkText(“somelink”)).click();
上面的代码可以帮助WebDriver识别对象并执行上面提到的动作
2) 点击下载链接后,firefox 浏览器会弹出一个下载对话框,里面有多个选项 像保存单选按钮,打开单选按钮,确定按钮,取消按钮以便使用它 您可以使用 Robot 类或 WebDriver 中的 Keys 喜欢
Robot r = new Robot();
r.KeyPress(KeyEvent.VK_TAB);
您可以多次使用上述代码来按下标签按钮
r.KeyRelease(KeyEvent.VK_TAB);
你必须松开按下的键
最后执行回车
r.KeyPress(KeyEvent.VK_ENTER);
点击下载链接时它会帮助您下载对象
希望对你有帮助
【讨论】: