java - 使用 Selenium/java 将网页保存为 PDF
问题描述
我正在尝试从 https://developers.google.com/speed/pagespeed/insights/下载页面速度报告。由于它没有“打印”选项,我需要使用 selenium 和 java 保存网页。我在这里有什么选择?
解决方案
一旦您成为 Page speed 页面之一,您就可以使用下面的代码来获取 innerHTML。
String htmlContent = driver.findElement(By.tagName("body")).getAttribute("innerHTML");
System.out.println(htmlContent);
如果您想将此字符串保存到 PDF 文件,请使用下面提到的库:
一旦你的项目中有提到的库。您可以使用以下代码:
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();
}
推荐阅读
- optaplanner - 在 OptaPlanner 的约束中使用 HardMediumSoftScore 时出现异常
- javascript - 如何在html标签中显示链接
- install4j - install4j v9.0后如何检测windows代理设置
- react-native - React Native-Styling Tab Navigator
- python - 如何在 Django ORM 中触发 bulk_create 之后的动作?
- node.js - 如何在 npm 中运行单个测试?
- reactjs - localStorage 需要时间在反应中存储令牌
- dataweave - 从 Dataweave 中的列中获取最大值
- postgresql - Postgres - 将列表拆分为行
- python - 列表理解中的三元运算符未按预期工作