Python + Selenium + PhantomJS 渲染为 PDF

标签 python selenium phantomjs

当 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/

相关文章:

python - 为什么我不能在 Django 模板 View 中使用连字符?

java - 如何使用 Selenium Web 驱动程序从文件系统拖放到浏览器

java - Selenium RC 和 Internet Explorer

java - 如何使用 java 将语言设置为 PhantomJs Ghostdriver?

javascript - CasperJS/PhantomJS 在加载页面时卡住

python - 类型错误 :ndarray not callable in scipy. stats.kstest()

jQuery 自动完成和 Flask

python - pandas:将数据帧减少到仅出现特定的事件链

python - 使用 Selenium 和 Python 查找存在 data-tb-test-id 属性而不是 id 的元素

java - 在 Serenity 上设置 PhantomJS webDriver