Is there a way to use PhantomJS in Python?

后端 未结 8 1295
死守一世寂寞
死守一世寂寞 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: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

提交回复
热议问题