当使用Selenium和Python结合使用PhantomJS时,是否可以利用PhantomJS的渲染到PDF的功能? (即通过Selenium在Python中模仿page.render('file.pdf')的行为)。
我知道这需要使用GhostDriver,而GhostDriver并没有真正支持打印功能。
如果有其他不依赖于Selenium的替代方案,请告诉我。
当使用Selenium和Python结合使用PhantomJS时,是否可以利用PhantomJS的渲染到PDF的功能? (即通过Selenium在Python中模仿page.render('file.pdf')的行为)。
我知道这需要使用GhostDriver,而GhostDriver并没有真正支持打印功能。
如果有其他不依赖于Selenium的替代方案,请告诉我。
以下是使用Selenium和GhostDriver的特殊命令的解决方案(自GhostDriver 1.1.0和PhantomJS 1.9.6以来,应该可以使用。已经在PhantomJS 1.9.8上测试通过):
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Download a webpage as a PDF."""
from selenium import webdriver
def download(driver, target_path):
"""Download the currently displayed page to target_path."""
def execute(script, args):
driver.execute('executePhantomScript',
{'script': script, 'args': args})
# hack while the python interface lags
driver.command_executor._commands['executePhantomScript'] = ('POST', '/session/$sessionId/phantom/execute')
# set page format
# inside the execution script, webpage is "this"
page_format = 'this.paperSize = {format: "A4", orientation: "portrait" };'
execute(page_format, [])
# render current page
render = '''this.render("{}")'''.format(target_path)
execute(render, [])
if __name__ == '__main__':
driver = webdriver.PhantomJS('phantomjs')
driver.get('http://stackoverflow.com')
download(driver, "save_me.pdf")
可以参考我对相同问题的回答这里。
selenium.selenium.capture_screenshot('file.png')
,但这将给你一个png格式的屏幕截图而不是pdf。似乎没有办法将屏幕截图保存为pdf。试过pdfkit了吗?它可以从html页面渲染PDF文件。
@rejected,我知道你提到不想使用子进程,但是...
理论上来说,你实际上可以利用子进程通信比你预期的要多。你可以采用 Ariya's stdin/stdout example,并将其扩展为一个相对通用的包装脚本。它可能首先接受要加载的页面,然后侦听(并执行)您在该页面上的测试操作。最终,您可以启动 .render
或甚至制作一个通用的错误处理捕获:
try {
// load page & execute stdin commands
} catch (e) {
page.render(page + '-error-state.pdf');
}
eval
来执行,而从我的尝试经验来看,这既不安全也不可靠。除非我错了? - Rejected