【问题标题】:downloading files behind javascript button with htmlunit使用 htmlunit 在 javascript 按钮后面下载文件
【发布时间】:2014-08-02 11:43:59
【问题描述】:

我正在尝试使用 HtmlUnit 下载 javascript 按钮后面的附件。执行其他任务效果很好(例如导航、登录)。 我检查了附件单元测试,但它没有帮助我。

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
}

但是,它会停止:

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

创建的文件大小为 0。 一定有办法找到附加的真实文件?!

提前谢谢你

【问题讨论】:

    标签: java download attachment htmlunit


    【解决方案1】:

    以防万一其他人想知道:您需要使用 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); 
                }
    

    【讨论】:

    • 您可以通过什么方式发布整个课程?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-11
    • 1970-01-01
    • 1970-01-01
    • 2014-09-27
    • 2020-05-22
    • 1970-01-01
    相关资源
    最近更新 更多