【问题标题】:Download CSV through HtmlUnit and read into array通过 HtmlUnit 下载 CSV 并读入数组
【发布时间】:2020-10-06 20:11:54
【问题描述】:

我有一个页面,该页面有一个按钮,用于下载 CSV 文件格式的信息。该按钮打开一个确认对话框以下载文件。我需要将该文件存储到一个临时位置(无论是内存还是保存到实际文件,然后将其删除),然后将 CSV 中的数据读取到数组中。

我已经尝试了这些问题中的代码(question 1question 2question 3question 4),但这并不是我所需要的 - 主要是因为他们没有下载 CSV 并使用里面的数据。

我不确定 ConfirmDialog 是否正在打开,但我确实添加了 ConfirmHandler 返回 true 以尝试下载文件。但是,我根本不知道文件在哪里下载。

这是我正在发生的事情以及我被卡住的地方:

我登录很好。我去一个报告生成器。我生成了一个在新窗口中打开的报告。新窗口打开得很好,我用WebWindowListener 抓住了它。然后我在新窗口中搜索“另存为 CSV”按钮。我可以找到它,我可以点击它,但是System.out.print 调用显示ConfirmHandler 没有触发。

for (DomElement e : newPage.getElementsByTagName("button")) {
    int i = 0;
    webClient.setConfirmHandler(new ConfirmHandler() {
        private static final long serialVersionUID = 1L;
        @Override
        public boolean handleConfirm(Page arg0, String arg1) {
            System.out.println("Test"); //isn't firing
            return false;
        }
    });
    if (((HtmlButton) e).getAttribute("onclick").contains("CSV")) {
        ((HtmlButton) e).click();
    }else {
        if (i++ == (newPage.getElementsByTagName("button").size() - 1)) throw new AssertionError("CSV button not found");
    }
}

【问题讨论】:

  • 抱歉,我们需要有关您的问题的更多详细信息。您在通过确认对话框时遇到问题吗?
  • 更新了我的问题。谢谢,我忘了提到确认对话框。

标签: java htmlunit


【解决方案1】:

这个答案的灵感来自this answer

我真的很想在不下载文件的情况下获取 CSV 信息,所以我在我的webWindowListenerwebWindowContentChanged(arg0) 方法中,只使用了arg0.getWebWindow().getEnclosingPage().getWebResponse().getContentAsString(),然后使用了几次String.split() 来获取我想要的信息。

下面是代码的样子,所以更清楚一点:

webClient.addWebWindowListener(new WebWindowListener() {

    @Override
    public void webWindowContentChanged(WebWindowEvent arg0) {
        if (CSVclicked) {           //boolean that is set true when I click the download button...
            String CSV = arg0.getWebWindow().getEnclosedPage().getWebResponse().getContentAsString();

            //do things...

            CSVclicked = false; //don't use the same behavior next time the method is called...
        }
    }
});

【讨论】:

    猜你喜欢
    • 2010-10-14
    • 2020-01-21
    • 2016-06-03
    • 2022-11-21
    • 1970-01-01
    • 2014-03-19
    • 1970-01-01
    • 2014-09-27
    • 1970-01-01
    相关资源
    最近更新 更多