我寻找通过GhostDriver使用PhantomJS渲染pdf的能力,而不仅仅是渲染pdf。当我使用下一个代码时,页面正常加载:
from selenium import webdriver
driver = webdriver.PhantomJS('./node_modules/phantomjs/bin/phantomjs')
driver.set_window_size(1024, 768)
driver.get('http://stackoverflow.com')当我通过命令行https://github.com/ariya/phantomjs/blob/master/examples/rasterize.js使用下一个脚本时,pdf生成得非常完美。
现在我想通过webdriver像rasterize.js (page.render('file.pdf'))一样执行脚本。webdriver具有execute_script方法,但它看起来像PhantomJS代码评估,不能访问webpage实例上下文。webdriver也有get_screenshot_as_base64方法,但它只返回png。
我使用的是最新版本的selenium、phantomjs、nodejs。
那么我的问题是如何通过GhostDriver访问PhantomJS网页实例并评估render方法?
发布于 2015-02-02 07:15:19
有一种特殊的方法可以从GhostDriver执行PhantomJS脚本,使用下面的命令:
POST /session/id/phantom/execute它包含在GhostDriver v1.1.0中,因此从PhantomJS v.1.9.6开始应该可以工作。
看看这个例子:
def execute(script, args):
driver.execute('executePhantomScript', {'script': script, 'args' : args })
driver = webdriver.PhantomJS('phantomjs')
# hack while the python interface lags
driver.command_executor._commands['executePhantomScript'] = ('POST', '/session/$sessionId/phantom/execute')
driver.get('http://stackoverflow.com')
# set page format
# inside the execution script, webpage is "this"
pageFormat = '''this.paperSize = {format: "A4", orientation: "portrait" };'''
execute(pageFormat, [])
# render current page
render = '''this.render("test.pdf")'''
execute(render, [])请注意,在OS X PhantomJS renders web page as images中,由于OS X中Qt渲染引擎的限制(至少在PhantomJS v.1.9.8及更早版本中),无法选择文本。
https://stackoverflow.com/questions/23125557
复制相似问题