Does anybody know how to launch the print dialog from chrome by selenium+python

谁说我不能喝 提交于 2019-12-23 04:36:07

问题


I have a question about how to launch the print dialog from chrome browser. I know the shortcut key to open this is ctrl+p, but I don't know how to describe it in selenium. Does anyone know this? Thanks a lot!

I tried the following code, but it doesn't work on my Chrome browser.

    actions = ActionChains(driver)
    actions.move_to_element(driver.find_element_by_tag_name('body'))
    actions.key_down(Keys.CONTROL).send_keys('T').key_up(Keys.CONTROL).perform()

回答1:


Not quite what you are asking about, but this is what worked for me in Firefox.

Send CTRL+P (or COMMAND+P on mac) to the body element using ActionChains:

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://google.com")

actions = ActionChains(driver)
actions.move_to_element(driver.find_element_by_tag_name('body'))
actions.key_down(Keys.CONTROL).send_keys('p').key_up(Keys.CONTROL)
actions.perform()



回答2:


Basically you need to trigger the JavaScript function that triggers the print pop-up. That function is window.print().

So what you need is to trigger that function after arriving at the page you want to print. So say you want to print the front page of stackoverflow.com

driver.get("https://stackoverflow.com")
# now you're at the page you want to print. Trigger print function
driver.execute_path("window.print()")

Now it should prompt you to the print pop-up. The reason you need to trigger the JavaScript function is because JavaScript is the browser's language.



来源:https://stackoverflow.com/questions/25902227/does-anybody-know-how-to-launch-the-print-dialog-from-chrome-by-seleniumpython

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!