2012-05-29 60 views
1

我在Selenium 2.21.0中使用Java 6.我如何使用Selenium WebDriver API在网页上下载文件?也就是说,有一个链接导致Excel文件的下载启动。我想知道如何启动下载,确定何时完成,然后找出文件下载到本地系统的位置。如何使用Java Selenium WebDriver下载文件?

+0

[这](http://sqa.stackexchange.com/questions/2197/how-do-i-download-a-file-using-seleniums-webdriver)可能帮帮我。 –

回答

0

一旦你点击任何链接下载文件,它取决于浏览器的行为,如 Chrome行为:一旦用户点击任何文件的链接,它将默认开始下载文件。 IE行为:IE在窗口底部显示一个栏并显示选项以保存或取消文件下载。 FireFox行为:这将显示一个对话框窗口并显示选项以保存或取消文件下载。 所以这可以通过FireFox Profile来实现。 在下载任何文件之前,您必须将文件的MIME类型传递给FireFox配置文件。 一些常用的MIME类型有: 文本文件(.txt) - 纯文本/ PDF文件(.PDF) - 应用程序/ PDF CSV文件(.csv) - 文本/ CSV MS Excel文件(。 XLSX) - 应用/ vnd.openxmlformats-officedocument.spreadsheetml.sheet MS字文件(.DOCX) - 应用/ 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(); 

希望它能解决您的疑问。快乐的编码。

0

我特别关注Firefox浏览器,当访问者点击任何下载链接时,您可以使用下载选项附带的弹出选项。它显示了两个按钮和两个单选按钮,可以让我们直接保存并打开文件,而无需事后下载,如果我们发现该文件很有用,我们可以通过Firefox浏览器上述工具栏上的下载图标明确下载。 所以,你可以执行以下步骤

1)点击下载链接

WebDriver driver = new FirefoxDriver(); 

driver.findElement(By.linkText(“somelink”)).click(); 

上面的代码可以帮助webdriver的识别对象并执行其中提到

2)的作用点击下载链接后,Firefox浏览器将弹出一个下载对话框,其中包含多个选项 Like Save单选按钮,打开单选按钮,ok按钮,取消按钮以便使用此 您可以使用Robot类或Keys WebDriver 像

Robot r = new Robot(); 


r.KeyPress(KeyEvent.VK_TAB); 

你可以使用尽可能多的时间在上面的代码按Tab键

r.KeyRelease(KeyEvent.VK_TAB); 

你必须放开按键

最后执行进入

r.KeyPress(KeyEvent.VK_ENTER); 

就是这样它会帮助你在下载链接被压制时下载对象使用sed

希望它会帮助你

相关问题