Python+Selenium+PhantomJS呈现为PDF

2024-09-26 22:10:37 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我意识到它使用GhostDriver,而GhostDriver在打印方式上并不真正支持。

如果另一种可能的替代品不是硒,我洗耳恭听。


Tags: 功能替代品pdfselenium方式pagephantomjsrender
3条回答

试过pdfkit?它可以从html页面呈现PDF文件。

您可以使用selenium.selenium.capture_screenshot('file.png'),但这将给您一个屏幕截图作为png而不是pdf。似乎没有办法获得pdf格式的截图。

这里是截图的文档:http://selenium.googlecode.com/git/docs/api/py/selenium/selenium.selenium.html?highlight=screenshot#selenium.selenium.selenium.capture_screenshot

下面是一个使用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

相关问题 更多 >

    热门问题