使用Selenium WebDriver使用Firefox"打印"或"另存为"功能

Dou*_*las 5 firefox selenium selenium-webdriver

我想以编程方式指示Firefox访问URL列表(例如,在文本文件中定义),并且每个URL都将页面保存到磁盘或打印它.

我知道Selenium提供了捕获页面截图的功能,但我想知道是否可以使用浏览器的本机保存和打印功能.

如果Selenium没有提供这样的功能,那么任何其他工具是否允许我定义一个由Firefox执行的脚本并获得类似的结果?

Fai*_*aiz 11

可以在firefox中启用静默打印以打印到默认打印机,绕过打印对话框.

所需的firefox首选项是print.always_print_silent,并且可以使用selenium设置,如下所示:

import org.openqa.selenium.JavascriptExecutor;
/* ... */
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("print.always_print_silent", true);
WebDriver driver = new FirefoxDriver(profile);
Run Code Online (Sandbox Code Playgroud)

现在只需导航到一个网页并使用javascript调用print:

driver.get("http://www.google.com");
((JavascriptExecutor)driver).executeScript("window.print();");
Run Code Online (Sandbox Code Playgroud)

此外,还可以使用免费的PDF打印机(如novaPDF)进行打印,而不显示"另存为"对话框,并自动将PDF保存到预定义位置.