Selenium未利用"--print-to-pdf"选项并打印到网络打印机



我正在构建一个Selenium驱动的脚本,该脚本可以访问一组网站并将它们直接下载到PDF。 当我在我们的办公室wifi上时,Chromium浏览器默认为它找到的网络打印机,而不是我设置的配置的"pdf"设置。

  1. 添加一组自定义首选项,将 Chromium 指向上次使用的打印设置 (pdf(。
  2. 添加 Chrome 参数 --kiosk-printing 和 --print-to-pdf
  3. 切换到另一个没有打印机的 wifi 网络(这与参数一起使用!

我使用以下方法初始化 Web 驱动程序:

def init_chromium():
    chrome_options = Options()
    chrome_options.add_argument("--kiosk-printing")
    chrome_options.add_argument("--print-to-pdf")
    chrome_driver = webdriver.Chrome(options=chrome_options)
    return chrome_driver

然后,我遍历要访问的页面列表,并使用JS打印带有用户提供的特殊"标签"的页面。

def page_navigation (driver, page_array, label):
    for i in page_array:
        print("Getting page {}".format(i))
        driver.get(i)
        driver.execute_script("document.title = '{}' + ' - ' + document.title".format(label))
        driver.execute_script("window.print();")
        print("Executed printing of {}.".format(i))

没有出现错误消息,但我需要一种方法来覆盖打印配置,无论我所在的网络如何。 在脚本的开头/结尾更改 wifi 网络并不理想。

经过一些测试,我注意到Chrome会选择位于我网络上的打印机并尝试打印给它们,无论我是否配置了它们 - 即使我提供了自己的用户配置。由于我们在办公室里有一个"访客"网络,我决定通过在刮板开始之前运行两个子流程来解决这个问题。

def check_network_and_printers():
    current_network=subprocess.run(["/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport", "-I"], capture_output=True)
    if "BAD NETWORK SSID" in str(current_network):
        logging.error("ERROR: This computer is connected to the BAD NETWORK SSID network.  Please switch to another network before re-running this program.")
        exit()
    current_printers=subprocess.run(["lpstat", "-s"], capture_output=True)
    if "No destinations added" not in str(current_printers):
            logging.error("ERROR:  Please remove any configured printers from your MacBook before running this script!")
            exit()

不是最好的解决方案,但是如果没有配置打印机,则Chrome将默认为所需的"打印到PDF"选项。 希望这对将来的某人有所帮助。:)

最新更新