我正在尝试分析PhantomJS中的锚链接(他们的text
属性)。
检索发生在这里:
var list = page.evaluate(function() {
return document.getElementsByTagName('a');
});
这将返回一个具有属性length
的对象,该对象很好(在控制台中运行length
时得到的document.getElementsByTagName('a');
)。但是对象中的绝大多数元素都具有null
的值,这并不好......我不知道为什么会这样。
我一直在玩转换到真正的数组slice
并没有好处。我尝试过不同的网站,没有区别。我已经转储了.png文件以验证是否正确加载并且网站已正确加载。
这显然不是完整的脚本,而是一个在众所周知的公共站点上显示问题的最小脚本;)
如何从加载的页面中检索完整的锚点列表?
var page = require('webpage').create();
page.onError = function(msg, trace)
{ //Error handling mantra
var msgStack = ['PAGE ERROR: ' + msg];
if (trace && trace.length) {
msgStack.push('TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function +'")' : ''));
});
}
console.error(msgStack.join('\n'));
};
phantom.onError = function(msg, trace)
{ //Error handling mantra
var msgStack = ['PHANTOM ERROR: ' + msg];
if (trace && trace.length) {
msgStack.push('TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + (t.file || t.sourceURL) + ': ' + t.line + (t.function ? ' (in function ' + t.function +')' : ''));
});
}
console.error(msgStack.join('\n'));
phantom.exit(1);
};
function start( url )
{
page.open( url , function (status)
{
console.log( 'Loaded' , url , ': ' , status );
if( status != 'success' )
phantom.exit( 0 );
page.render( 'login.png');
var list = page.evaluate(function() {
return document.getElementsByTagName('a');
});
console.log( 'List length: ' , list.length );
for( var i = 0 ; i < list.length ; i++ )
{
if( !list[i] )
{
console.log( i , typeof list[i] , list[i] === null , list[i] === undefined );
//list[i] === null -> true for the problematic anchors
continue;
}
console.log( i, list[i].innerText , ',' , list[i].text /*, JSON.stringify( list[i] ) */ );
}
//Exit with grace
phantom.exit( 0 );
});
}
start( 'http://data.stackexchange.com/' );
//start( 'http://data.stackexchange.com/account/login?returnurl=/' );
答案 0 :(得分:3)
当前版本的phantomjs只允许原始类型(布尔值,字符串,数字,[]
和{}
)传递到页面上下文和从页面上下文传递。所以基本上所有函数都将被剥离,这就是DOM元素。来自t.niese found the quote:
注意: evaluate函数的参数和返回值必须是一个简单的原始对象。经验法则:如果它可以通过JSON序列化,那就没关系了。
闭包,函数,DOM节点等不起作用!
您需要在页面上下文中完成部分工作。如果你想要每个节点的innerText
属性,那么你需要先将它映射到基本类型:
var list = page.evaluate(function() {
return Array.prototype.map.call(document.getElementsByTagName('a'), function(a){
return a.innerText;
});
});
console.log(list[0]); // innerText
您当然可以同时映射多个属性:
return Array.prototype.map.call(document.getElementsByTagName('a'), function(a){
return { text: a.innerText, href: a.href };
});