【问题标题】:Use Firefox 'print' or 'save as' features using Selenium WebDriver使用 Selenium WebDriver 使用 Firefox 的“打印”或“另存为”功能
【发布时间】:2020-11-24 21:09:17
【问题描述】:

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

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

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

【问题讨论】:

    标签: firefox selenium selenium-webdriver


    【解决方案1】:

    可以在 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);
    

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

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

    此外,将它与免费的 PDF 打印机(如 novaPDF)结合到print without displaying the Save as dialog 并自动将 PDF 保存到预定义的位置。

    【讨论】:

    • print.always_print_silent 就像一个魅力。我正在尝试将此与 Microsoft PDF 打印机结合使用,但我很难将纸张更改为 A4。我都尝试过:将print.printer_Microsoft_Print_to_PDF.print_paper_data 设置为9print.printer_Microsoft_Print_to_PDF.print_paper_name 设置为iso_a4,但两者似乎都被忽略了,因为我可以在about:config 上看到它们的默认值
    【解决方案2】:

    通常您会使用Sikuli API 来执行此操作。开源社区(又名 Mozilla 基金会)正在开发一个名为 Marionette 的项目,据称该项目可以让你在不使用屏幕截图匹配的情况下完成这些事情,但它仍然是 alpha 版,他们仍在努力,Chrome 和 IE 尚未登录它还没有。

    应该注意的是,在本地文件下载中,您实际上并不需要测试已经经过良好测试的另存为对话框的浏览器功能。 Selenium 测试人员通常所做的只是使用 Apache HttpUtils 或类似的东西下载文件,然后在下载步骤中绕过浏览器。然后你就不需要使用另存为对话框,它可以跨浏览器工作。只需使用 selenium 获取下载 URL,然后使用 Java 代码下载即可。

    【讨论】:

      【解决方案3】:

      如果你对png格式没问题,你可以全屏截图。

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

      【讨论】:

        【解决方案4】:

        也许这可以帮助你...... https://stackoverflow.com/a/64987078/6003328

        我用 python 做了这个... 基本上,我更改了每次打印的 about:config 设置,调整要创建的 pdf 的文件名,并将打印机设置为 always_print_silent: true...

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-11-28
          • 2015-11-27
          • 1970-01-01
          • 2013-01-11
          相关资源
          最近更新 更多