使用htmlunit按钮onclick下载文件

时间:2017-11-15 21:44:02

标签: selenium selenium-webdriver webdriver htmlunit htmlunit-driver

我需要在点击按钮后下载一个文件,在java中使用selenium的htmlunit。我遇到的问题是,在模拟按钮单击后,下载的内容将返回整个html而不是实际文件。以下是我要遵循的步骤:

在我的html / javascript中,我创建了使用单独按钮上传和下载json的功能,如下所示。它可以在任何Web浏览器(chrome / firefox / ie)

中按预期工作

上传按钮

 <button id="loadJson" class="button" onclick="$('#upload').click()" title="Reload JSON"></button> 
 <form enctype="multipart/form-data" id="upload-form" style="display: none">
   <input id="upload" type=file accept=".json" name="files[]" size=30></form>

下载按钮:(下载对话框打开,用于指定文件名和保存位置)

<button id="saveJson" class="button" onclick="testUtil.save()" title="Save JSON"></button>

我使用以下代码模拟htmlunit中的上传:

   String webUrl="http://localhost:8000/";
    HtmlUnitDriver driver = new HtmlUnitDriver(BrowserVersion.CHROME);
    WebClient webClient = new WebClient();
    webClient.getOptions().setJavaScriptEnabled(false);
    HtmlPage page = webClient.getPage(webUrl);
    System.out.println(page.getByXPath(".//*[@id='upload']").get(0).toString());
    HtmlFileInput input =(HtmlFileInput) page.getByXPath(".//*[@id='upload']").get(0);
    input.setValueAttribute("C:\\My_files\\test.json");

之后,我想下载我上传的文件

HtmlButton button= (HtmlButton) page.getByXPath(".//*[@id='saveJson']").get(0);
System.out.println(button.toString());

验证我是否已选择输入:我将此视为上述打印语句的输出

    HtmlButton[<button id="saveJson" class="button" onclick="testUtil.save()"
 title="Save JSON">]

然后我尝试下载并保存:

InputStream is = button.click().getWebResponse().getContentAsStream();  
byte[] buffer = new byte[is.available()];
        is.read(buffer);
        File targetFile = new File("C:\\My_files\\new.json");
        OutputStream outStream = new FileOutputStream(targetFile);
        outStream.write(buffer);

当我查看输出文件时,它不会返回json,但它只返回html页面的内容(index.html)。我真的不确定我错过了什么。

任何有硒htmlunitdriver经验的人,请指导调试此问题吗?

0 个答案:

没有答案