保存从互联网的Excel文件
我正在尝试使用Selenium从站点下载Excel文件。
我这样做的方式:
WebElement excelList = driver.findElement(By.xpath("...")); excelList.click(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); String pageSource = driver.getPageSource(); FileOutputStream fos = new FileOutputStream("d:/load.xls"); for (int i = 0; i < pageSource.length(); i++) { char c = pageSource.charAt(i); fos.write((byte) c); } fos.close();
页面源string长度等于我从这个站点手动下载的文件大小。
问题是我不正确地保存数据和MS Excel无法打开保存的文件。
如何正确保存文件?
你可以尝试使用String.getBytes()
来重新编码字符stream重新编码字节stream,但可能仍然不会工作。
基本上,为了把excel文件的二进制数据保存在一个string中,数据必须使用字符集进行解码。 因为excel文件不应该被看作纯文本,所以可能有很多字节序列是无效的字符编码。 这些字节序列解码为String
时可能只是表示为'?' (尽pipe这取决于实际使用的Charset
)。 当您尝试使用String.getBytes()
或其他方法重新编码字符'?' 字符不会转换回原始字节,而是转换为unicode问号字符的编码,这对于excel文件格式几乎肯定无效。
真正的问题是,为什么你需要通过Se下载这个文件? Se是testing浏览器如何呈现网页。 如果你需要Excel文件,为什么不直接从链接中获取href,然后使用一个简单的HttpUrlConnection
来使用标准的二进制InputStream
下载文件?
我想到了。
我只需要点击加载文件button后从最后一页获取inputstream。 但是获取页面对象“lastPage()”的方法已经保护了访问。
方法如下:
private static void saveExcelFile(HtmlUnitDriver driver) { Method m = driver.getClass().getDeclaredMethod("lastPage", null); m.setAccessible(true); Object obj = m.invoke(driver, null); Page page = (Page) obj; InputStream stream = page.getWebResponse().getContentAsStream(); FileOutputStream fos = new FileOutputStream("d:/load.xls"); int c; while ((c = stream.read()) != -1) { fos.write(c); } fos.close(); }