首页 > 解决方案 > 使用 Selenium/java 将网页保存为 PDF

问题描述

我正在尝试从 https://developers.google.com/speed/pagespeed/insights/下载页面速度报告。由于它没有“打印”选项,我需要使用 selenium 和 java 保存网页。我在这里有什么选择?

标签: javaselenium

解决方案


一旦您成为 Page speed 页面之一,您就可以使用下面的代码来获取 innerHTML。

String htmlContent = driver.findElement(By.tagName("body")).getAttribute("innerHTML");
System.out.println(htmlContent);

如果您想将此字符串保存到 PDF 文件,请使用下面提到的库:

https://pdfbox.apache.org/

一旦你的项目中有提到的库。您可以使用以下代码:

PdfDocument doc = new PdfDocument();
try {
  doc.load("your pdf file path");  
  // Write text at position (100, 100) on page 1
  doc.writeText(
    htmlContent,
    100, // x-coordinate
    50); // y-coordinate
   
  doc.save("your pdf file path");
  doc.close();
} catch (IOException | PdfException e) {
  e.printStackTrace();
}

推荐阅读