【问题标题】:How to run webpage code with PhantomJS via GhostDriver (selenium)如何通过 GhostDriver (selenium) 使用 PhantomJS 运行网页代码
【发布时间】:2014-06-01 06:39:09
【问题描述】:

我通过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')) 的脚本。 webdriverexecute_script 方法,但它看起来像 PhantomJS 代码评估并且无权访问 webpage 实例上下文。 webdriver 也有 get_screenshot_as_base64 方法,但它只返回 png。

我使用最新版本的seleniumphantomjsnodejs

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

【问题讨论】:

  • 我也在找这个,还有……有人吗?
  • 对于 PDF 生成(不是 GhostDriverWebDriver),您可以使用 ghost.py(需要 QT),找到带有 pyexecjssubprocesses 的包装器。还存在作为pdfkitwkhtmltopdf 的python 包作为wkhtmltopdf 的包装器 - 它应该具有相同的结果,因为webkit 也是如此。 weasyprint 也不错,但不是 webkit。

标签: python selenium phantomjs ghostdriver


【解决方案1】:

有一种特殊的方法可以从 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 和更早版本中),因此无法选择文本。

【讨论】:

  • 对于非 python 实现呢?有没有办法在 Java 或除 python 之外的任何其他实现中做到这一点?
猜你喜欢
  • 2015-04-04
  • 2012-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-24
  • 1970-01-01
  • 2012-01-19
相关资源
最近更新 更多