使用Selenium WebDriver使用Firefox的“打印"或“另存为"功能 [英] Use Firefox 'print' or 'save as' features using Selenium WebDriver

查看:459
本文介绍了使用Selenium WebDriver使用Firefox的“打印"或“另存为"功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to programatically instruct Firefox to visit a list of URLs (defined in a text file, for instance) and for each of them save the page to disk or print it.

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

I know Selenium provides a feature to capture a screenshot of the page, but I would like to know if it's possible to use browser's native saving and printing features.

如果Selenium不提供此类功能,是否可以使用其他任何工具来定义要由Firefox执行的 script 并获得相似的结果?

If Selenium does not provide such features, would any other tool allow me to define a script to be executed by Firefox and achieve similar results?

推荐答案

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

It is possible to enable silent printing in firefox to print to the default printer, bypassing the print dialog.

所需的firefox首选项为print.always_print_silent,并且可以使用硒进行设置,如下所示:

The required firefox preference is print.always_print_silent, and can be setup with selenium like so:

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

现在只需导航到网页并使用javascript调用打印:

Now simply navigate to a web page and call print using javascript:

driver.get("http://www.google.com");
((JavascriptExecutor)driver).executeScript("window.print();");

此外,将其与免费的PDF打印机(例如novaPDF)耦合到,并自动将PDF保存到预定义的位置.

Additionally, couple this with a free PDF printer such as novaPDF to print without displaying the Save as dialog and automatically save a PDF to a predefined location.

这篇关于使用Selenium WebDriver使用Firefox的“打印"或“另存为"功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆