Rej*_*ted 21 python selenium phantomjs
PhantomJS's
当PhantomJS与Selenium和Python结合使用时,是否可以使用渲染到PDF功能?(即page.render('file.pdf')
通过Selenium 模仿Python内部的行为).
我意识到这种用途GhostDriver
,并GhostDriver
没有真正支持打印的方式.
如果另一种替代品可能不是Selenium,我全都耳朵.
MTu*_*ner 11
这是一个使用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")
Run Code Online (Sandbox Code Playgroud)
另见我在这里回答同一个问题.
小智 1
你可以使用selenium.selenium.capture_screenshot('file.png')
,但这会给你一个 png 格式的屏幕截图,而不是 pdf 格式。似乎没有办法获取 pdf 格式的屏幕截图。
以下是 capture_screenshot 的文档:http://selenium.googlecode.com/git/docs/api/py/selenium/selenium.selenium.html ?highlight=screenshot#selenium.selenium.selenium.capture_screenshot
归档时间: |
|
查看次数: |
10864 次 |
最近记录: |