如何通过GhostDriver(Selenium)使用PhantomJS运行网页代码 [英] How to run webpage code with PhantomJS via GhostDriver (selenium)

查看:89
本文介绍了如何通过GhostDriver(Selenium)使用PhantomJS运行网页代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找通过GhostDriverPhantomJS渲染pdf的能力,而不仅仅是渲染pdf.当我使用下一个代码时,通常会加载页面:

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')

当我通过命令行 https://github使用下一个脚本时. com/ariya/phantomjs/blob/master/examples/rasterize.js ,然后完美生成pdf.

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

现在,我想通过webdriver执行类似rasterize.js(page.render('file.pdf'))的脚本. webdriver具有execute_script方法,但是它看起来像PhantomJS代码评估,并且不能访问webpage实例上下文. webdriver也具有get_screenshot_as_base64方法,但它仅返回png.

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.

我使用的是seleniumphantomjsnodejs的最新版本.

I use latest versions of selenium, phantomjs, nodejs.

所以我的问题是如何通过GhostDriver访问PhantomJS网页实例并评估render方法?

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

推荐答案

有一种特殊的方法可以使用下一条命令从GhostDriver执行PhantomJS脚本:

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

POST /session/id/phantom/execute

它已包含在 GhostDriver v1.1.0 中,因此自 PhantomJS v.1.9.6 .

It was included in GhostDriver v1.1.0, so it should work since 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中,将网页呈现为图像,其中包含无法选择的文本,由于OS X中Qt渲染引擎的限制(至少在PhantomJS v.1.9.8及更早版本中).

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).

这篇关于如何通过GhostDriver(Selenium)使用PhantomJS运行网页代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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