首页 文章

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

提问于
浏览
199

我想在Python中使用PhantomJS . 我搜索了这个问题,但找不到合适的解决方案 .

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

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

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

8 回答

  • 39

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

    • 安装NodeJS

    • 使用Node的软件包管理器安装phantomjs: npm -g install phantomjs-prebuilt

    • 安装selenium(在你的virtualenv中,如果你正在使用它)

    安装后,您可以使用幻像,如下所示:

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

    如果系统路径环境变量不是't set correctly, you',则需要将确切路径指定为 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')
    

    参考文献:

  • 4

    PhantomJS最近dropped Python support . 然而,PhantomJS现在嵌入Ghost Driver .

    此后,一个新项目加紧填补空白: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
    
  • 80

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

    我按照Pykler的建议尝试了PhantomJS的Node安装,但实际上我发现它比PhantomJS的独立安装慢 . 我想独立安装没有提前提供这些功能,但从v1.9开始,它就是这样做的 .

    现在你可以像这样使用

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

    以下是我使用PhantomJS和Django测试javascript的方法:

    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

  • 8

    这就是我所做的,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')
    
  • 5

    如果使用Anaconda,请安装:

    conda install PhantomJS
    

    在你的脚本中:

    from selenium import webdriver
    driver=webdriver.PhantomJS()
    

    工作得很好 .

  • 4

    answer by @Pykler很棒,但节点要求已过时 . 该答案中的评论提出了更简单的答案,我在这里为了节省其他时间而放在这里:

    • 安装PhantomJS

    正如@ Vivin-Paliath指出的那样,它是一个独立的项目,而不是Node的一部分 .

    苹果电脑:

    brew install phantomjs
    

    Ubuntu的:

    sudo apt-get install phantomjs
    

    等等

    • 设置 virtualenv (如果您还没有):
    virtualenv mypy  # doesn't have to be "mypy". Can be anything.
    . mypy/bin/activate
    

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

    • 安装硒:
    pip install selenium
    
    • 尝试一个简单的测试,就像从_1582356中借来的那样:
    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()
    
  • 1

    如果您使用的是Buildout,则可以使用gp.recipe.node配方轻松自动化Pykler描述的安装过程 .

    [nodejs]
    recipe = gp.recipe.node
    version = 0.10.32
    npms = phantomjs
    scripts = phantomjs
    

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

    driver = webdriver.PhantomJS('bin/phantomjs')
    

相关问题