首页 > 解决方案 > 硒打印不起作用(打印到 PDF)

问题描述

我想要 selenium:打开一个页面,休眠 10 秒(确保所有内容都已加载),然后打印网页。这两种解决方案都不是,使用javascript打印页面,或者使用send_keys作品。

profile = FirefoxProfile(PATH_TO_PROFILE_HERE)
profile.set_preference("print.always_print_silent", True)
profile.set_preference("print.printer_Microsoft_Print_to_PDF.print_to_file", True)
profile.set_preference("print.printer_Microsoft_Print_to_PDF.print_to_filename", file_location)
driver = webdriver.Firefox(profile)

driver.get(URL_HERE)
time.sleep(10)

# Neither one of these two seem to work.
# driver.execute_script('window.print();')
# driver.find_element_by_css_selector("body").send_keys(Keys.CONTROL, "p")

当我手动进入问题页面(使用带有适当设置的首选项的配置文件)时,我可以使用Ctrl+P它并且它在没有关于打印位置/命名它的对话框的情况下打印。

问题是间歇性的,它可以在www.google.com其他网站上运行,但不能运行?有没有人找到一种方法让打印工作 100% 的时间?

相关问题:在 chrome 中将网页自动打印/保存为 pdf - python 2.7

标签: pythonseleniumselenium-webdriverprinting

解决方案


您可以尝试使用以下命令,而不是使用 selenium:

https://pypi.org/project/pdfkit/0.4.1/

然后这段代码:

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

推荐阅读