How to run webpage code with PhantomJS via GhostDriver (selenium)

大兔子大兔子 提交于 2019-11-27 04:43:58

问题


I looking for ability render pdf with PhantomJS via GhostDriver, not just render pdf. When I use next code, then page normally loaded:

from selenium import webdriver

driver = webdriver.PhantomJS('./node_modules/phantomjs/bin/phantomjs')
driver.set_window_size(1024, 768)
driver.get('http://stackoverflow.com')

When I use next script via command line https://github.com/ariya/phantomjs/blob/master/examples/rasterize.js then pdf generated perfectly.

Now I want execute script like rasterize.js (page.render('file.pdf')) but via webdriver. webdriver has execute_script method but it look like PhantomJS code evaluation and do not have access to webpage instance context. Also webdriver has get_screenshot_as_base64 method, but it return only png.

I use latest versions of selenium, phantomjs, nodejs.

So my question how I can get access to PhantomJS webpage instance via GhostDriver and evaluate render method?


回答1:


There is a special way to execute PhantomJS script from GhostDriver, using the next command:

POST /session/id/phantom/execute

It was included in GhostDriver v1.1.0, so it should work since PhantomJS v.1.9.6.

Look at this example:

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, [])

Note that in OS X PhantomJS renders web page as images with not selectable text, due to limitations of Qt rendering engine in OS X (at least with PhantomJS v.1.9.8 and earlier).



来源:https://stackoverflow.com/questions/23125557/how-to-run-webpage-code-with-phantomjs-via-ghostdriver-selenium

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!