如何使用python与打印框进行交互



我一直在使用硒自动打印文档,但我被困在打印屏幕上。据我所知,硒不与打印屏幕相互作用,所以我正在寻找一种可以与硒一起使用的替代情况。到目前为止,我的代码在下面,我所需要的只是让我选择新打印机然后打印的代码。我还想将该打印机更改为另存为 PDF,然后将 pdf 保存到文件中,所以如果这给了我一个快捷方式,那会有很大帮助。

from selenium import webdriver
from selenium import *
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
driver = webdriver.Remote(
command_executor='http://127.0.0.1:4444/wd/hub',
desired_capabilities=DesiredCapabilities.CHROME) #This is because I am using remote web driver for my Mac, but it is the same as regular web driver
driver.execute("window.print()")
#Need code here

我使用了window.print((,然后执行了一个包含必要js命令的python字符串:print_function = ''' let A = document.getElementsByTagName('print-preview-app')[0].shadowRoot; let B = A.getElementById('sidebar').children[0].shadowRoot; let C = B.getElementById('button-strip').children[0] C.click() ''' driver.execute_script(print_function)

请记住,您还需要使用 driver.swich_to.window(window_handles[i]( 来确保您与打印框进行交互。

一旦你进入一个shadowRoot元素,你就没有可用的driver.find_element_by方法的全部补充。 当您在shadowRoot中进行搜索时,您只能使用通过JS提供的方法。

找到一个可能适合你的建议。 如何使用Python将网页转换为PDF

也许尝试pdfkit

import pdfkit
pdfkit.from_url('http://google.com', 'out.pdf')

最新更新