Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/380.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在linux上使用Selenium IDE下载文件对话_Java_Linux_Selenium - Fatal编程技术网

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

Java 如何在linux上使用Selenium IDE下载文件对话,java,linux,selenium,Java,Linux,Selenium,我必须自动完成一个测试,在这个测试中我必须下载一份excel表格。屏幕上会出现一个带有“确定”和“取消”按钮的文件对话框,单击“确定”按钮将下载一份excel表格。我使用Java作为自动化语言,我的操作系统是Linux。请建议如何自动完成此案例。我也在不同的论坛中搜索过,我发现AutoIt是一种用于基于windows的组件的脚本语言…但我现在使用的是Linux,因此AutoIt在我的情况下无法工作..任何帮助plz???使用selenium下载对话框都是一个真正的麻烦,因为selenium无法与

我必须自动完成一个测试,在这个测试中我必须下载一份excel表格。屏幕上会出现一个带有“确定”和“取消”按钮的文件对话框,单击“确定”按钮将下载一份excel表格。我使用Java作为自动化语言,我的操作系统是Linux。请建议如何自动完成此案例。我也在不同的论坛中搜索过,我发现AutoIt是一种用于基于windows的组件的脚本语言…但我现在使用的是Linux,因此AutoIt在我的情况下无法工作..任何帮助plz???

使用selenium下载对话框都是一个真正的麻烦,因为selenium无法与对话框交互。简言之,可能的工作方式是创建一个自定义firefox配置文件,用户在下载特定mimetype文件时不会收到提示,该文件将自动下载到您指定的文件夹中。然后,您必须告诉selenium应该使用哪个配置文件。如果不这样做,selenium将以匿名配置文件启动firefox。不幸的是,根据firefox和selenium的不同版本,具体步骤似乎有所不同。我希望这些链接可以帮助:


下载带有selenium的对话框真是让人头疼,因为selenium无法与对话框交互。简言之,可能的工作方式是创建一个自定义firefox配置文件,用户在下载特定mimetype文件时不会收到提示,该文件将自动下载到您指定的文件夹中。然后,您必须告诉selenium应该使用哪个配置文件。如果不这样做,selenium将以匿名配置文件启动firefox。不幸的是,根据firefox和selenium的不同版本,具体步骤似乎有所不同。我希望这些链接可以帮助:

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

大多数想下载文件的人这样做只是为了展示一个下载文件的自动化框架,因为这会让一些人成为非技术性的ooo和ahh

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

只有当你真的要对文件做些什么的时候才下载文件,如果你是为了下载而下载文件,那你就是在浪费测试时间、网络带宽和磁盘空间

如果您想继续下载文件,尽管存在上述问题,我建议您不要使用Selenium IDE,而是使用WebDriver API

以下是我使用Java的实现:

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

一般来说,它工作良好,具有跨平台/跨浏览器的兼容性

代码是:

 /*
* 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();
    }
}
/*
*版权所有(c)2010-2011 Ardesco解决方案-http://www.ardescosolutions.com
*
*根据Apache许可证2.0版(以下简称“许可证”)获得许可;
*除非遵守许可证,否则不得使用此文件。
*您可以通过以下方式获得许可证副本:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*除非适用法律要求或书面同意,软件
*根据许可证进行的分发是按“原样”进行分发的,
*无任何明示或暗示的保证或条件。
*请参阅许可证以了解管理权限和权限的特定语言
*许可证下的限制。
*/
包com.lazerycode.ebselen.customhandlers;
导入com.google.common.annotations.Beta;
导入com.lazerycode.ebselen.EbselenCore;
导入com.lazerycode.ebselen.handlers.FileHandler;
导入org.apache.commons.httpclient.*;
导入org.apache.commons.httpclient.cookie.CookiePolicy;
导入org.apache.commons.httpclient.httpclient;
导入org.apache.commons.httpclient.methods.GetMethod;
导入java.io.*;
导入java.net.URL;
导入java.util.Set;
导入org.openqa.selenium.WebDriver;
导入org.openqa.selenium.WebElement;
导入org.slf4j.Logger;
导入org.slf4j.LoggerFactory;
@贝塔
公共类文件下载程序{
私有静态最终记录器Logger=LoggerFactory.getLogger(EbselenCore.class);
私有网络驱动程序;
私有字符串downloadPath=System.getProperty(“java.io.tmpdir”);
公共文件下载程序(WebDriver driverObject){
this.driver=driverObject;
}
/**
*获取文件将下载到的当前位置。
*
*@返回文件将下载到的文件路径。
*/
公共字符串getDownloadPath(){
返回此.downloadPath;
}
/**
*设置文件将下载到的路径。
*
*@param filePath文件将下载到的文件路径。
*/
public void setDownloadPath(字符串文件路径){
this.downloadPath=文件路径;
}
/**
*加载WebDriver当前知道的所有cookie,以便我们可以模拟浏览器cookie状态
*
*@param seleniumCookieSet
*@返回
*/
私有HttpState MIMICookieState(设置seleniumCookieSet){
HttpState mimicWebDriverCookieState=新HttpState();
对于(org.openqa.selenium.Cookie seleniumCookie:seleniumCookieSet){
Cookie httpClientCookie=新Cookie(seleniumCookie.getDomain()、seleniumCookie.getName()、seleniumCookie.getValue()、seleniumCookie.getPath()、seleniumCookie.getExpiry()、seleniumCookie.isSecure());
mimicWebDriverCookieState.addCookie(httpClientCookie);
}
返回mimicWebDriverCookieState;
}
/**
*模拟WebDriver主机配置
*
*@param hostURL
*@返回
*/
私有主机配置mimicHostConfiguration(字符串hostURL,int hostPort)