Download file using HtmlUnit

后端 未结 6 2002
一生所求
一生所求 2021-02-05 23:17

I am trying to download xls file for a website. When I click the link to download the file, I get a javascript confirm box. I handle it like below

    ConfirmHan         


        
6条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-05 23:39

    Figure out the download URL, and scrape it in List. from the download url we can get the entire file using this code.

        try{
            String path = "your destination path";
            List downloadfiles = (List) page.getByXPath("the tag you want to scrape");
            if (downloadfiles.isEmpty()) {
                System.out.println("No items found !");
            } else {
                for (HtmlElement htmlItem : downloadfiles) {
                    String DownloadURL = htmlItem.getHrefAttribute();
    
                    Page invoicePdf = client.getPage(DownloadURL);
                    if (invoicePdf.getWebResponse().getContentType().equals("application/pdf")) {
                        System.out.println("creatign PDF:");
                        IOUtils.copy(invoicePdf.getWebResponse().getContentAsStream(),
                                new FileOutputStream(path + "file name"));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    

提交回复
热议问题