当 PhantomJS 与 Selenium 和 Python 结合使用时,是否可以使用 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")
另请参阅我对同一问题的回答 here .
关于Python + Selenium + PhantomJS 渲染为 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16927090/