如何让Selenium逃脱Chrome中的自动打印对话框,以将页面打印为pdf?

时间:2019-04-29 21:10:05

标签: python html selenium pdf printing

我正在努力弄清楚如何使用Selenium将页面打印为pdf。单击该按钮后,我要的页面将打开一个打印对话框。有什么办法可以关闭Chrome中的该对话框,以便我可以将页面本身另存为pdf?我已经在StackOverflow上看到driver.execute_script("window.print = function(){};")禁用了打印,但这似乎不起作用。 这是我当前的代码

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


driver = webdriver.Chrome()
driver.implicitly_wait(5)  # wait for page to load for 5 secs

driver.get('https://printatestpage.com/')
window_before = driver.window_handles[0]
print(driver.title)
driver.execute_script("window.print = function(){};")
colour_test_page = driver.find_element_by_id('PrintColor')
colour_test_page.click()
driver.implicitly_wait(5)
window_after = driver.window_handles[1]
driver.switch_to.window(window_after)
print(driver.title)
webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform()

对话框将打开,但是什么也没有发生。非常感谢您的帮助!

0 个答案:

没有答案