【问题标题】:PhantomJS running a script against a specific HTML file?PhantomJS 针对特定的 HTML 文件运行脚本?
【发布时间】:2015-07-26 23:58:23
【问题描述】:

PhantomJS 拥有有史以来最糟糕的文档。如何针对特定的 html 文件运行简单的 .js?如果我运行 phantomjs,我可以使用 REPL 接口运行require。如何以 window. 设置为好像特定 html 文件是目标的方式运行它?

我想做类似的事情

var $ = require('jquery');
$("div").attr('class');

并获取类的列表......反对这个......

<html>
  <head><title>Hello World</title></title>
  <body>
    <div class="foo bar baz"> </div>
  </body>
</html>

【问题讨论】:

    标签: jquery unit-testing phantomjs automated-tests headless-browser


    【解决方案1】:

    基于numerous examples:

    'use strict';
    
    var page = require('webpage').create();
    
    page.open('your-file.html', function (status) {
        if (status !== 'success') {
            console.log('Unable to load file');
            phantom.exit(1);
        }
    
        page.includeJs('https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js', function () {
            page.onConsoleMessage = function (message) {
                console.log(message);
            };
    
            page.evaluate(function () {
                console.log($('div').attr('class'));
            });
    
            phantom.exit();
        });
    });
    

    我以前从未使用过 PhantomJS,这花了 10 分钟。仔细看!

    【讨论】:

    • 除非你使用 .includeJs 这不是我想要测试的 CommonJS...碰巧知道如何在那里获得require('module')
    • @EvanCarroll 注入 requireJS 然后使用 require 来要求 jQuery。 requre 在页面上下文中不可用,jQuery 在页面上下文之外没有意义。
    【解决方案2】:

    您不必为此使用 jquery。工作示例:

    var classes = [].map.call(document.querySelectorAll("div"),
                             function(el){ return el.className; });
    

    【讨论】:

      猜你喜欢
      • 2018-12-08
      • 1970-01-01
      • 2011-05-13
      • 1970-01-01
      • 1970-01-01
      • 2021-12-12
      • 2017-08-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多