这是我正在运行的脚本:
//Require CasperJS
var casper = require('casper').create();
//Scraping Courserank
var base = "https://www.courserank.com";
var home = base + "/w/home";
var schools = base + "/w/schools?switchSchool=1";
//First, navigate to homepage and login
casper.start(home, function() {
console.log('Logging in...');
//Fill in the login form
this.fill(
'form[action="login"]',
{ username : '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="afc7cedbcdc0d6dccec2efc8c2cec6c381ccc0c2" rel="noreferrer noopener nofollow">[email protected]</a>', password : "****" },
true
);
});
function getSchools() {
var arr = document.querySelectorAll('div.link');
return arr;
}
//Go to the schools page
casper.then(function() {
console.log(this.getCurrentUrl());
//Open the school choice page
casper.open(schools).then(function() {
console.log(this.getCurrentUrl());
//Get all school links
var schools_arr = this.evaluate(getSchools);
console.log(schools_arr.length);
Array.prototype.map.call(schools_arr, function(elem) {
console.log(elem.innerHTML);
});
});
});
casper.run();
一切都很顺利,直到 map 调用的内部循环,特别是console.log(elem.innerHTML)
。 schools_arr
中的许多元素均为 null。如果我在 console.log
语句周围添加一个 if(elem != null) { ... }
,一切都很好,但这违背了要点。当我在页面上的 Chrome 控制台中运行相同的 document.querySelectorAll
时,NodeList 中的 513 个元素都不为 null。 CasperJS 还报告了 513 个元素,但其中许多显示为 null。这里发生了什么?页面未完全加载?我以前从未使用过 CasperJS,如果这是一个新手错误,我很抱歉。
最佳答案
您无法使用evaluate()
从页面上下文返回 native 节点元素;你必须Array#map
到可使用JSON.parse
反序列化的东西。
因此,您的 getSchools()
函数应该执行以下操作:
function getSchools() {
var arr = document.querySelectorAll('div.link');
return Array.prototype.map.call(arr, function(elem) {
return elem.innerHTML;
});
}
虽然我不知道你可以用节点innerHTML字符串内容做什么......所以通常最好将元素映射到你需要的确切属性:
function getSchools() {
var arr = document.querySelectorAll('div.link a');
return Array.prototype.map.call(arr, function(elem) {
return elem.getAttribute('href');
});
}
编辑:根据评论中的要求,获取所有链接的内部文本:
function getSchools() {
var arr = document.querySelectorAll('div.link a');
return Array.prototype.map.call(arr, function(elem) {
return elem.textContent;
});
}
关于javascript - CasperJS 在 NodeList 中返回 null 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14794919/