首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何通过GhostDriver (selenium)用PhantomJS运行网页代码

如何通过GhostDriver (selenium)用PhantomJS运行网页代码
EN

Stack Overflow用户
提问于 2014-04-17 13:51:48
回答 1查看 6K关注 0票数 8

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

代码语言:javascript
复制
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生成得非常完美。

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

我使用的是最新版本的seleniumphantomjsnodejs

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

EN

回答 1

Stack Overflow用户

发布于 2015-02-02 07:15:19

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

代码语言:javascript
复制
POST /session/id/phantom/execute

它包含在GhostDriver v1.1.0中,因此从PhantomJS v.1.9.6开始应该可以工作。

看看这个例子:

代码语言:javascript
复制
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及更早版本中),无法选择文本。

票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23125557

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档