Python + Selenium + PhantomJS渲染为PDF [英] Python + Selenium + PhantomJS render to PDF

查看:89
本文介绍了Python + Selenium + PhantomJS渲染为PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当PhantomJS与Selenium和Python结合使用时,是否可以使用PhantomJS's呈现PDF功能? (即通过Selenium模拟Python中的page.render('file.pdf')行为).

Is it possible to use PhantomJS's rendering to PDF capabilities when PhantomJS is being used in combination with Selenium and Python? (ie. mimic page.render('file.pdf') behaviour inside Python via Selenium).

我意识到这使用了GhostDriver,而GhostDriver并没有真正支持很多打印方式.

I realize that this uses GhostDriver, and GhostDriver doesn't really support much in the way of printing.

如果还有其他可能不是硒的替代品,那我全都听了.

If another alternative is possible that isn't Selenium, I'm all ears.

推荐答案

以下是使用硒和针对GhostDriver的特殊命令的解决方案 (从GhostDriver 1.1.0和PhantomJS 1.9.6开始,并通过PhantomJS 1.9.8进行了测试,它应该可以正常工作):

Here is a solution using selenium and special command for GhostDriver (it should work since GhostDriver 1.1.0 and PhantomJS 1.9.6, tested with 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")

也可以在此处看到我对相同问题的回答.

see also my answer to the same question here.

这篇关于Python + Selenium + PhantomJS渲染为PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆