首页 文章

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

提问于
浏览
8

我通过 GhostDriver 寻找能力渲染pdf与 PhantomJS ,而不仅仅是渲染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生成完美 .

现在我想要执行脚本,如 rasterize.jspage.render('file.pdf') )但是通过 webdriver . webdriverexecute_script 方法,但它看起来像 PhantomJS 代码评估,并且无法访问 webpage 实例上下文 . 另外 webdriverget_screenshot_as_base64 方法,但它只返回png .

我使用 seleniumphantomjsnodejs 的最新版本 .

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

1 回答

  • 9

    有一种特殊的方法可以使用下一个命令从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及更早版本),因此文本不可选 .

相关问题