【问题标题】:Selenium not utilizing "--print-to-pdf" option and printing to network printersSelenium 未使用“--print-to-pdf”选项并打印到网络打印机
【发布时间】:2019-07-08 21:12:02
【问题描述】:

我正在构建一个由 Selenium 提供支持的脚本,该脚本可以访问一组网站并将它们直接下载到 PDF 中。当我在我们的办公室 wifi 上时,Chromium 浏览器默认使用它找到的网络打印机,而不是我设置的已配置的“pdf”设置。

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

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

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 网络并不理想。

【问题讨论】:

  • 我认为--print-to-pdf 仅在您以无头模式运行时可用。
  • 很好的标注!很抱歉没有早点看到。

标签: python python-3.x selenium selenium-chromedriver


【解决方案1】:

经过一些测试,我注意到 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”选项。希望这可以帮助将来的人。 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-10
    • 1970-01-01
    • 2011-04-12
    • 2013-01-22
    • 2017-04-21
    • 1970-01-01
    • 2012-05-28
    • 2011-04-13
    相关资源
    最近更新 更多