Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
有没有办法在Python中使用PhantomJS?_Python_Phantomjs - Fatal编程技术网

有没有办法在Python中使用PhantomJS?

有没有办法在Python中使用PhantomJS?,python,phantomjs,Python,Phantomjs,我想用在。我用谷歌搜索了这个问题,但找不到合适的解决办法 我发现os.popen()可能是一个不错的选择。但我无法向它传递一些论据 目前,使用subprocess.Popen()可能是一个合适的解决方案。我想知道是否有更好的解决办法 有没有一种方法可以在Python中使用PhantomJS?PhantomJS。然而,PhantomJS现在嵌入了 此后,一个新项目开始填补这一空白:。您可能想用它来代替: from ghost import Ghost ghost = Ghost() with g

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

我发现
os.popen()
可能是一个不错的选择。但我无法向它传递一些论据

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

有没有一种方法可以在Python中使用PhantomJS?

PhantomJS。然而,PhantomJS现在嵌入了

此后,一个新项目开始填补这一空白:。您可能想用它来代替:

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

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

移动/测试没有错误。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);
});
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
mobile/tests.py

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);
});
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
运行测试

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);
});
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

manage.py test mobile

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

  • 安装
  • 使用节点的包管理器安装phantomjs:
    npm-g安装phantomjs预构建的
  • 安装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')
    
    参考资料:


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

    按照Pykler的建议,我尝试了PhantomJS的节点安装,但实际上我发现它比PhantomJS的独立安装慢。我猜独立安装之前没有提供这些功能,但从v1.9开始,它就提供了很多功能

  • 安装PhantomJS()(如果您在Linux上,以下说明将有所帮助)
  • 使用pip安装Selenium
  • 现在你可以这样用了

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

    我就是这么做的,蟒蛇3.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')
    
    command=“phantomjs——忽略ssl错误=true”+
    process=subprocess.Popen(命令,shell=True,stdout=subprocess.PIPE)
    #确保phantomjs有时间下载/处理页面
    #但如果30秒后我们什么也没得到,继续前进
    尝试:
    输出,错误=进程。通信(超时=30)
    例外情况除外,如e:
    打印(“\t\t异常:%s”%e)
    process.kill()
    #输出将是怪异的,解码到utf-8以避免心痛
    幻象_输出=“”
    对于输出中的out_行。拆分行():
    幻象输出+=输出线解码('utf-8')
    
    如果您正在使用,您可以轻松地自动化Pykler使用配方描述的安装过程

    该部分将node.js作为二进制文件安装(至少在我的系统上),然后使用npm安装PhantomJS。最后,它创建一个入口点
    bin/phantomjs
    ,您可以使用它调用phantomjs webdriver。(要安装Selenium,您需要在egg要求或构建配置中指定它。)


    如果使用Anaconda,请使用以下设备安装:

    conda install PhantomJS
    
    在脚本中:

    from selenium import webdriver
    driver=webdriver.PhantomJS()
    
    工作完美

    这一点很好,但节点要求已经过时。该答案中的评论建议了一个更简单的答案,我在这里提出这个答案是为了节省其他人的时间:

  • 安装PhantomJS

    正如@Vivin palith指出的,它是一个独立的项目,不是Node的一部分

    Mac:

    Ubuntu:

    sudo apt-get install phantomjs
    

  • 设置
    virtualenv
    (如果尚未设置):

    如果您的计算机同时具有Python2和Python3,则可能需要运行
    virtualenv-3.6mypy
    或类似程序

  • 安装selenium:

    pip install selenium
    
  • 尝试一个简单的测试,如借用的:


  • 谢谢我使用subprocess.Popen调用phantomjs脚本,它成功了:)你看到这是如何限制的了吧?你所做的只是调用一个shell来执行phantomjs——实际上你并没有使用一个“合适的”接口,通过这个接口你可以正确地处理异常、阻塞等情况。@kamelkev:我明白这是多么的有限。好处是,这种方法允许我使用Django的bootstraping特性为每个测试设置具有正确内容的测试数据库。是的,它可以与其他答案相结合,以实现两个方面的最佳效果。尽管支持被放弃,但我发现安装npm(节点包管理器)并使用它安装最新的phantomjs(支持webdriver)和在python中安装selenium。。。这比让PyQT或PySide正常工作要容易得多。phantom的优点是它确实是无头的,并且不需要与UI/X11相关的LIB来工作。我在下面添加了一个答案,解释了我在尝试使用ghost.py和Hatting my lifePykler的“Hatting my life”后的首选解决方案。如果有人把这个问题的“正确答案”改成派克勒的,我会省下一天的努力。@YPCrumble:不幸的是,只有OP能做到这一点;更改已接受的答案。今天早上,在尝试了一系列不同的方法之后,@Pykler解决方案以最流畅的方式结束了工作。这非常有效,可能为我节省了几天时间。非常感谢。如果想要将整个呈现的页面作为源代码返回,那么它就是driver.page\u source。这确实工作得很好,我感到非常惊喜,因为上面说“不是Node.js模块”——但的npm包装器使它能够实现这一目的。在我的例子中,我想这样做:
    bodyStr=driver。通过标签名称(“body”)查找元素。获取属性(“innerHTML”)
    ,然后……它就成功了!我同意ghost具有疯狂的依赖性,事实上,即使在安装了数百万个与X11相关的库之后,我也无法启动并运行它。鬼是一个恐怖的故事。@phabtar您需要传递到phantomjs的路径作为phantomjs的第一个参数。。。或者修复您的windows系统路径以便能够看到phantomjs。愚蠢的问题:为什么我必须安装NodeJS?是
    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    
    driver = webdriver.PhantomJS()
    driver.get("http://www.python.org")
    assert "Python" in driver.title
    elem = driver.find_element_by_name("q")
    elem.clear()
    elem.send_keys("pycon")
    elem.send_keys(Keys.RETURN)
    assert "No results found." not in driver.page_source
    driver.close()