我想在Python中使用PhantomJS。我用谷歌搜索了这个问题,但找不到合适的解决办法。

我发现os.popen()可能是一个不错的选择。但是我不能给它传递一些参数。

现在使用subprocess.Popen()可能是一个合适的解决方案。我想知道是否有更好的解决办法。

有办法在Python中使用PhantomJS吗?


当前回答

在python中使用PhantomJS最简单的方法是通过Selenium。最简单的安装方法是

安装NodeJS 使用Node的包管理器安装phantomjs: npm -g install phantomjs-prebuilt 安装selenium(在您的virtualenv中,如果您正在使用它)

安装完成后,你可以简单地使用phantom:

from selenium import webdriver

driver = webdriver.PhantomJS() # or add to your PATH
driver.set_window_size(1024, 768) # optional
driver.get('https://google.com/')
driver.save_screenshot('screen.png') # save a screenshot to disk
sbtn = driver.find_element_by_css_selector('button.gbqfba')
sbtn.click()

如果你的系统路径环境变量没有正确设置,你将需要指定准确的路径作为webdriver.PhantomJS()的参数。替换:

driver = webdriver.PhantomJS() # or add to your PATH

... 与以下:

driver = webdriver.PhantomJS(executable_path='/usr/local/lib/node_modules/phantomjs/lib/phantom/bin/phantomjs')

引用:

http://selenium-python.readthedocs.io/ 如何在python webdriver中为phantomjs/ghostdriver设置代理? https://dzone.com/articles/python-testing-phantomjs

其他回答

这就是我所做的,python3.3。我正在处理庞大的站点列表,因此超时失败对于工作运行整个列表是至关重要的。

command = "phantomjs --ignore-ssl-errors=true "+<your js file for phantom>
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)

# make sure phantomjs has time to download/process the page
# but if we get nothing after 30 sec, just move on
try:
    output, errors = process.communicate(timeout=30)
except Exception as e:
    print("\t\tException: %s" % e)
    process.kill()

# output will be weird, decode to utf-8 to save heartache
phantom_output = ''
for out_line in output.splitlines():
    phantom_output += out_line.decode('utf-8')

下面是我如何使用PhantomJS和Django测试javascript:

移动/ 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);
});

移动/ 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

运行测试:

py测试移动设备

现在,由于GhostDriver与PhantomJS捆绑在一起,通过Selenium使用它变得更加方便了。

我尝试了Pykler建议的PhantomJS的Node安装,但实际上我发现它比独立安装PhantomJS要慢。我猜独立安装之前没有提供这些特性,但是从v1.9开始,它就提供了很多特性。

安装PhantomJS (http://phantomjs.org/download.html)(如果你在Linux上,下面的说明将有助于https://stackoverflow.com/a/14267295/382630) 使用pip安装Selenium。

现在你可以这样用

import selenium.webdriver
driver = selenium.webdriver.PhantomJS()
driver.get('http://google.com')
# do some processing

driver.quit()

PhantomJS最近完全放弃了对Python的支持。然而,PhantomJS现在嵌入了幽灵驱动程序。

一个新的项目填补了这一空白:ghost.py。你可能想用它来代替:

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

在python中使用PhantomJS最简单的方法是通过Selenium。最简单的安装方法是

安装NodeJS 使用Node的包管理器安装phantomjs: npm -g install phantomjs-prebuilt 安装selenium(在您的virtualenv中,如果您正在使用它)

安装完成后,你可以简单地使用phantom:

from selenium import webdriver

driver = webdriver.PhantomJS() # or add to your PATH
driver.set_window_size(1024, 768) # optional
driver.get('https://google.com/')
driver.save_screenshot('screen.png') # save a screenshot to disk
sbtn = driver.find_element_by_css_selector('button.gbqfba')
sbtn.click()

如果你的系统路径环境变量没有正确设置,你将需要指定准确的路径作为webdriver.PhantomJS()的参数。替换:

driver = webdriver.PhantomJS() # or add to your PATH

... 与以下:

driver = webdriver.PhantomJS(executable_path='/usr/local/lib/node_modules/phantomjs/lib/phantom/bin/phantomjs')

引用:

http://selenium-python.readthedocs.io/ 如何在python webdriver中为phantomjs/ghostdriver设置代理? https://dzone.com/articles/python-testing-phantomjs