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

后端 未结 1 2023
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-06 12:27

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



        
1条回答
  •  半阙折子戏
    2020-12-06 12:41

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

    0 讨论(0)
提交回复
热议问题