【问题标题】:File download in Selenium webdriver using robot class使用机器人类在 Selenium webdriver 中下载文件
【发布时间】:2017-06-16 14:28:12
【问题描述】:

当我点击下载按钮时,它会在 Firefox 中打开一个下载弹出窗口。它运行正确并保存文件,但是当我在循环中迭代时,它不保存而是打开文件。下面提到的代码有什么解决方案吗?

for (int j = 0; j < StoreSelectedYear_size; j++) {
            System.out.println(StoreSelectedYear.get(j));
            YearSelection(StoreSelectedYear.get(j));
            Thread.sleep(5000);

            filedownload(i);

        }
        StoreSelectedYear.clear();
    }

}

public void YearSelection(String StoreSelectedYearStr) throws InterruptedException, AWTException {
    Select yearselction = new Select(driver.findElement(By.cssSelector("#u14_input")));
    yearselction.selectByVisibleText(StoreSelectedYearStr);
    Thread.sleep(5000);

}

public void filedownload(int i) throws AWTException, InterruptedException {
    driver.findElement(By.xpath("//button[@id='export']")).click();
    Thread.sleep(6000);
    Robot robot = new Robot();
    robot.delay(5000);
    // Thread.sleep throws InterruptedException

    if (i == 0) {
        robot.keyPress(KeyEvent.VK_DOWN);
        robot.delay(2000);
        robot.keyPress(KeyEvent.VK_TAB);

        robot.keyPress(KeyEvent.VK_TAB);

        robot.keyPress(KeyEvent.VK_TAB);

        robot.keyPress(KeyEvent.VK_ENTER);

    }

Firefox 保存图片:

【问题讨论】:

  • 您的问题陈述没有告诉我们您遇到的问题。请使用正确的问题陈述和您面临的错误来编辑问题,以便更好地调试。

标签: java selenium-webdriver selenium-firefoxdriver


【解决方案1】:

您可以尝试另一种解决方案,方法是获取下载元素的 src 属性,然后使用 http 库(例如 HttpUnit)直接请求下载文件。

这有一个额外的好处,如果您需要在测试中验证或操作它(如果它与您的用例匹配),它将更容易将文件作为对象提供给您。

我建议这样做,因为如果您是为了工作而这样做,那么使用不需要操纵屏幕坐标和窗口位置的解决方案通常总是更好的选择。而且测试下载提示可能没有什么价值,因为它在您的应用程序的沙盒中不存在。

您可以使用此代码检索当前 selenium 测试会话使用的 cookie,以防万一这对您有吸引力。

Set<Cookie> seleniumCookies = driver.manage().getCookies();
    org.apache.http.client.CookieStore cookieStore = new org.apache.http.client.BasicCookieStore();

    for (Cookie seleniumCookie : seleniumCookies) {
        org.apache.http.impl.cookie.BasicClientCookie basicClientCookie =
                new BasicClientCookie(seleniumCookie.getName(), seleniumCookie.getValue());
        basicClientCookie.setDomain(seleniumCookie.getDomain());
        basicClientCookie.setExpiryDate(seleniumCookie.getExpiry());
        basicClientCookie.setPath(seleniumCookie.getPath());
        cookieStore.addCookie(basicClientCookie);
    }

    return cookieStore;

这实际上会将您的 cookie 转换为 apache http 库可用的形式,您可以使用它向您的应用程序发出请求,而应用程序不会意识到您已退出 selenium。如果您的请求对本示例中的 cookie 进行了更改,那么您可以在之后使用新版本重新设置 selenium 中的 cookie。

【讨论】:

    猜你喜欢
    • 2011-08-02
    • 1970-01-01
    • 1970-01-01
    • 2012-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-16
    相关资源
    最近更新 更多