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>
答案 0 :(得分:2)
'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分钟。看起来更难!
答案 1 :(得分:-2)
您不必使用jquery。工作示例:
var classes = [].map.call(document.querySelectorAll("div"),
function(el){ return el.className; });