使用htmlunit下载javascript按钮后面的文件 [英] downloading files behind javascript button with htmlunit

查看:162
本文介绍了使用htmlunit下载javascript按钮后面的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用HtmlUnit下载一个JavaScript按钮后面的附件。执行其他任务非常有用(例如导航,登录)。
我签出了附件单元测试,但没有帮助我。

I am trying to download something an attachment behind a javascript button with HtmlUnit. Performing other tasks works great (eg. navigating, login). I checked out the attachment unit test but it didnt help me.

final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_24);
final HtmlPage page1 = webClient.getPage( loginUrl );
final HtmlTextInput textField =  page1.getElementByName(user);
final HtmlPasswordInput pwd =  page1.getElementByName(pwd);  
textField.setValueAttribute(User.getUsername());
pwd.setValueAttribute(User.getPassword());   

final HtmlSubmitInput button =  page1.getElementByName(login);
final HtmlPage page2 =  button.click();

String buttonJavaScript = "window.location='"+folder+filename + ....... ";
ScriptResult result = page2.executeJavaScript(buttonJavaScript);
webClient.waitForBackgroundJavaScript(2000);    

InputStream is = result.getNewPage().getWebResponse().getContentAsStream();
try {
    File f = new File("filename.extension");
    OutputStream os = new FileOutputStream(f);
    byte[] bytes = new byte[1024];
    while (read == is.read(bytes)) {
        os.write(bytes, 0, read);
    }
    os.close();
    is.close();
} catch (IOException ex) {
    // Exception handling
}

但是,它停止: / p>

However, it stops with:

runtimeError: message=[No node attached to this object] sourceName=[http://pagead2.googlesyndication.com/pagead/osd.js] line=[7] lineSource=[null] lineOffset=[0]

该文件创建的是大小0.
必须有一种方法才能到达真实的文件附加?!

The file created is size 0. There must be a way to get to the real file attached?!

提前谢谢你

推荐答案

只要有人想知道:你需要使用AttachmentHandler。

Just in case anyone else is wondering: You need to use the AttachmentHandler.

            ScriptResult result = page2.executeJavaScript(buttonJavaScript);
            webClient.waitForBackgroundJavaScript(1000);

            if( attachments.size() > 0 )
            {
                Attachment attachment = attachments.get(0);

                Page attachedPage = attachment.getPage();
                WebResponse attachmentResponse = attachedPage.getWebResponse();

                String content = attachmentResponse.getContentAsString();

                ... write(content); 
            }

这篇关于使用htmlunit下载javascript按钮后面的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆