问题
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