java - 如何在 Linux 上使用 Selenium IDE 下载文件对话框

标签 java linux selenium

我必须自动执行一个测试,我必须在其中下载一个 excel 表。屏幕上会出现一个文件对话框,其中包含“确定”和“取消”按钮,然后单击“确定”按钮下载一个 excel 表。我正在使用 Java 作为自动化语言和我的操作系统是 Linux ..请建议如何自动化这个案例..我也在不同的论坛中搜索过,并且发现 AutoIt 作为基于 Windows 的组件的脚本语言......但是我在这里使用 Linux 所以 AutoIt 会在我的情况下不起作用..有什么帮助吗??

最佳答案

Link to my blog where I discuss this in more detail.

首先为什么要下载文件?你打算用它做些什么吗?

大多数想要下载文件的人只是这样做,以便他们可以显示一个下载文件的自动化框架,因为它会让一些非技术人员呜呜呜啊啊啊。

您可以检查标题响应以检查您是否获得 200 OK(或者可能是重定向,取决于您的预期结果)并且它会告诉您文件存在。

仅当您确实要对文件执行某些操作时才下载文件,如果您下载文件是为了执行此操作,那么您就是在浪费测试时间、网络带宽和磁盘空间。

尽管有上述情况,如果您仍想继续下载文件,我建议的解决方案是不使用 Selenium IDE,而是使用 WebDriver API。

这是我使用 Java 实现的:

https://github.com/Ardesco/Ebselen/blob/master/ebselen-core/src/main/java/com/lazerycode/ebselen/customhandlers/FileDownloader.java

这会在页面上找到链接并提取链接到的 url。然后它使用 apache commons 复制 selenium 使用的浏览器 session ,然后下载文件。在某些情况下它不起作用(在页面上找到的链接实际上并没有链接到下载文件,而是一个防止自动文件下载的层)。

通常它运行良好并且是跨平台/跨浏览器兼容的。

代码是:

 /*
* Copyright (c) 2010-2011 Ardesco Solutions - http://www.ardescosolutions.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.lazerycode.ebselen.customhandlers;

import com.google.common.annotations.Beta;
import com.lazerycode.ebselen.EbselenCore;
import com.lazerycode.ebselen.handlers.FileHandler;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;

import java.io.*;
import java.net.URL;
import java.util.Set;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Beta
public class FileDownloader {

    private static final Logger LOGGER = LoggerFactory.getLogger(EbselenCore.class);
    private WebDriver driver;
    private String downloadPath = System.getProperty("java.io.tmpdir");

    public FileDownloader(WebDriver driverObject) {
        this.driver = driverObject;
    }

    /**
* Get the current location that files will be downloaded to.
*
* @return The filepath that the file will be downloaded to.
*/
    public String getDownloadPath() {
        return this.downloadPath;
    }

    /**
* Set the path that files will be downloaded to.
*
* @param filePath The filepath that the file will be downloaded to.
*/
    public void setDownloadPath(String filePath) {
        this.downloadPath = filePath;
    }


    /**
* Load in all the cookies WebDriver currently knows about so that we can mimic the browser cookie state
*
* @param seleniumCookieSet
* @return
*/
    private HttpState mimicCookieState(Set<org.openqa.selenium.Cookie> seleniumCookieSet) {
        HttpState mimicWebDriverCookieState = new HttpState();
        for (org.openqa.selenium.Cookie seleniumCookie : seleniumCookieSet) {
            Cookie httpClientCookie = new Cookie(seleniumCookie.getDomain(), seleniumCookie.getName(), seleniumCookie.getValue(), seleniumCookie.getPath(), seleniumCookie.getExpiry(), seleniumCookie.isSecure());
            mimicWebDriverCookieState.addCookie(httpClientCookie);
        }
        return mimicWebDriverCookieState;
    }

    /**
* Mimic the WebDriver host configuration
*
* @param hostURL
* @return
*/
    private HostConfiguration mimicHostConfiguration(String hostURL, int hostPort) {
        HostConfiguration hostConfig = new HostConfiguration();
        hostConfig.setHost(hostURL, hostPort);
        return hostConfig;
    }

    public String fileDownloader(WebElement element) throws Exception {
        return downloader(element, "href");
    }

    public String imageDownloader(WebElement element) throws Exception {
        return downloader(element, "src");
    }

    public String downloader(WebElement element, String attribute) throws Exception {
        //Assuming that getAttribute does some magic to return a fully qualified URL
        String downloadLocation = element.getAttribute(attribute);
        if (downloadLocation.trim().equals("")) {
            throw new Exception("The element you have specified does not link to anything!");
        }
        URL downloadURL = new URL(downloadLocation);
        HttpClient client = new HttpClient();
        client.getParams().setCookiePolicy(CookiePolicy.RFC_2965);
        client.setHostConfiguration(mimicHostConfiguration(downloadURL.getHost(), downloadURL.getPort()));
        client.setState(mimicCookieState(driver.manage().getCookies()));
        HttpMethod getRequest = new GetMethod(downloadURL.getPath());
        FileHandler downloadedFile = new FileHandler(downloadPath + downloadURL.getFile().replaceFirst("/|\\\\", ""), true);
        try {
            int status = client.executeMethod(getRequest);
            LOGGER.info("HTTP Status {} when getting '{}'", status, downloadURL.toExternalForm());
            BufferedInputStream in = new BufferedInputStream(getRequest.getResponseBodyAsStream());
            int offset = 0;
            int len = 4096;
            int bytes = 0;
            byte[] block = new byte[len];
            while ((bytes = in.read(block, offset, len)) > -1) {
                downloadedFile.getWritableFileOutputStream().write(block, 0, bytes);
            }
            downloadedFile.close();
            in.close();
            LOGGER.info("File downloaded to '{}'", downloadedFile.getAbsoluteFile());
        } catch (Exception Ex) {
            LOGGER.error("Download failed: {}", Ex);
            throw new Exception("Download failed!");
        } finally {
            getRequest.releaseConnection();
        }
        return downloadedFile.getAbsoluteFile();
    }
}

关于java - 如何在 Linux 上使用 Selenium IDE 下载文件对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9970959/

相关文章:

linux - 如何在 Linux 中编写一个程序,它会在我打开计算机时自动运行?

php - 无法使用 PHP 创建的管道写入 C 应用程序的 STDIN

ios - Python 3 错误 : ImportError: No module named selenium

java - 整数 i=3 vs 整数 i= 新整数 (3)

java - Android Adapter 中的 overridePendingTransition 方法

java - 使类线程安全

java - 使用 Selenium 截屏

java - 如何为框架设置彩色背景?

Linux 开放问题

java - 如何使用 java WebDriver 在 Firefox 中打开 "about:preferences"