Use Firefox 'print' or 'save as' features using Selenium WebDriver

10,558

Solution 1

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

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);

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

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

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.

Solution 2

Normally you would do this using Sikuli API. The open source community (a.k.a. Mozilla foundation) is working on a project called Marionette that supposedly will enable you do do these things without using screenshot matching but it's still alpha and they are still working on it and Chrome and IE haven't signed onto it yet.

It should be noted that on native file downloads, you don't really need to test the browser functionality of the already well tested save-as dialog. What Selenium testers usually do is just download the file with Apache HttpUtils or something similar and just bypass the browser on the download step. Then you don't need to use the Save-As dialog and it will work cross-browser. Just use selenium to get the download URL and download it with Java code instead.

Solution 3

If you are fine with png format, you can take full page screenshot.

import selenium.webdriver
import selenium.common

options = selenium.webdriver.firefox.options.Options()
# options.headless = True
with selenium.webdriver.Firefox(options=options) as driver:
    driver.get('http://google.com')
    time.sleep(2)
    root=driver.find_element_by_tag_name('html')
    root.screenshot('full page screenshot.png')
Share:
10,558
Pesha
Author by

Pesha

Updated on June 14, 2022

Comments

  • Pesha
    Pesha almost 2 years

    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.

    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.

    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?