首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在linux上使用Selenium IDE下载文件对话

如何在linux上使用Selenium IDE下载文件对话
EN

Stack Overflow用户
提问于 2012-04-02 12:36:02
回答 3查看 7.5K关注 0票数 1

我必须自动执行一个测试,在该测试中我必须下载excel工作表。.屏幕上会出现一个文件对话框,单击“确定”和“取消”按钮,然后单击“确定”按钮将下载excel工作表。.我使用Java作为自动化语言,我的操作系统是Linux..Please,建议如何自动执行此操作。.我也在不同的论坛中搜索过,发现AutoIt是基于component...but的windows脚本语言。我使用的是Linux,因此AutoIt在我的case..Any帮助中不起作用?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-04-02 13:17:21

使用selenium下载对话框是一件令人头疼的事情,因为selenium不能与对话框交互。简而言之,创建一个自定义的firefox配置文件,用户在下载特定mimetype类型的文件时不会得到提示,文件将自动下载到您指定的文件夹中。然后您必须告诉selenium它应该使用哪个配置文件。如果不这样做,selenium将使用匿名配置文件启动firefox。不幸的是,不同版本的firefox和selenium的确切步骤似乎有所不同。我希望这些链接能有所帮助:

票数 1
EN

Stack Overflow用户

发布于 2012-04-02 21:11:59

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

首先,你为什么要下载这个文件?你要用它做点什么吗?

大多数想要下载文件的人只是这样做,这样他们就可以展示一个下载文件的自动化框架,因为这会让一些非技术人员感到不知所措。

你可以检查头部响应,检查你是否得到了200OK(或者重定向,这取决于你的预期结果),它会告诉你一个文件存在。

只有当你真的要用它们做一些事情时才下载文件,如果你是为了这样做而下载它们的,那么你就是在浪费测试时间、网络带宽和磁盘空间。

如果您想继续下载文件,尽管有上述情况,我建议解决方案是不使用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使用的浏览器会话,然后下载文件。在某些情况下,它不会起作用(页面上的链接实际上并没有链接到下载文件,而是一个层,以防止自动文件下载)。

一般来说,它工作得很好,并且跨平台/跨浏览器顺从。

代码是:

代码语言:javascript
运行
复制
 /*
* 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();
    }
}
票数 2
EN

Stack Overflow用户

发布于 2013-01-18 16:31:03

我必须在相当严格的设置中解决这个问题:任务是测试生成的PDF的内容,即:

  1. 不可通过任何直接URL或FTP提供,但可在jQuery请求时直接流式传输到浏览器。
  2. HTTP标头强制打开/保存对话。(我的意思是系统对话,粗糙的)
  3. 最后一个痛处是目标浏览器的IE8。因此,上面提到的解决方案都不适用于我。

我找到的解决方案几乎是微不足道的。可以使用键盘在对话框中导航并打开窗口。我记下了我需要敲击的键的顺序

焦点打开文件= tab+tab+enter

  • save本地磁盘上的文件=焦点+{键入绝对路径}+enter

  • 关闭下载的文件= alt+f4

  • switch

= alt+tab

我甚至可以通过序列ctrl+A+ctrl+C复制文档的字符串内容,然后通过java.awt.Toolkit.getDefaultToolkit().getSystemClipboard();从系统剪贴板中读取它

当然,这个序列取决于环境和浏览器,你需要让它“智能”。

我相信两个事实: 1. Selenium总是运行在本地主机上,所以我可以通过FileInputStream打开保存的文件,并对它做任何我想做的事情。生成MD5,比较二进制文件,使用专用库打开它,或者只是保留它以进行手动测试。2.我可以预测哪个窗口将获得焦点。(当下载对话框打开时,filePathField会获得焦点,这样我就可以在其中键入路径。)

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9970959

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档