Is there a way to use PhantomJS in Python?

后端 未结 8 1305
死守一世寂寞
死守一世寂寞 2020-11-22 08:05

I want to use PhantomJS in Python. I googled this problem but couldn\'t find proper solutions.

I find os.popen() may be a good choice. But I couldn\'t

相关标签:
8条回答
  • 2020-11-22 08:25

    PhantomJS recently dropped Python support altogether. However, PhantomJS now embeds Ghost Driver.

    A new project has since stepped up to fill the void: ghost.py. You probably want to use that instead:

    from ghost import Ghost
    ghost = Ghost()
    
    with ghost.start() as session:
        page, extra_resources = ghost.open("http://jeanphi.me")
        assert page.http_status==200 and 'jeanphix' in ghost.content
    
    0 讨论(0)
  • 2020-11-22 08:37

    Here's how I test javascript using PhantomJS and Django:

    mobile/test_no_js_errors.js:

    var page = require('webpage').create(),
        system = require('system'),
        url = system.args[1],
        status_code;
    
    page.onError = function (msg, trace) {
        console.log(msg);
        trace.forEach(function(item) {
            console.log('  ', item.file, ':', item.line);
        });
    };
    
    page.onResourceReceived = function(resource) {
        if (resource.url == url) {
            status_code = resource.status;
        }
    };
    
    page.open(url, function (status) {
        if (status == "fail" || status_code != 200) {
            console.log("Error: " + status_code + " for url: " + url);
            phantom.exit(1);
        }
        phantom.exit(0);
    });
    

    mobile/tests.py:

    import subprocess
    from django.test import LiveServerTestCase
    
    class MobileTest(LiveServerTestCase):
        def test_mobile_js(self):
            args = ["phantomjs", "mobile/test_no_js_errors.js", self.live_server_url]
            result = subprocess.check_output(args)
            self.assertEqual(result, "")  # No result means no error
    

    Run tests:

    manage.py test mobile

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