节点列表数组仅 returns 第一个元素
Array of node list only returns the first element
我正在使用 PhantomJS 抓取一些数据
var root = this;
var a = [];
page.open('https://www.thegioididong.com/dtdd/iphone-x-256gb', function (status) {
page.evaluateAsync(function () {
console.log("click now")
document.getElementsByClassName("viewparameterfull")[0].click()
}, 3000)
setTimeout(function (a, b) {
root.a = page.evaluate(function (el, i) {
console.log("get data now")
var temp = document.getElementsByClassName('parameterfull')[0].childNodes
for (i = 0; i < temp.length; i++) {
console.log(temp[i].innerHTML)
}
//Output html of all childNodes as intended
return temp
})}
, 10000)
})
setTimeout(function () {
console.log("log now");
for (i = 0; i < a.length; i++) {
console.log(a[i].innerHTML)
}
//Output only the first child of a, but a.length still shows 51 (enough number of child nodes)
console.log(a)
}, 20000)
通过子节点到控制台的第一个循环有效 - 它将每个子节点打印到控制台上
但是第二个循环似乎不起作用 - 它只打印第一个值并显示错误 TypeError: null is not an object (evaluating 'a[i].innerHTML')
这里有什么问题?
根据 PhantomJS docs,page.evaluate()
的 return 值必须是 JSON-serializable。我猜 PhantomJS 的 DOM 节点的内部表示不是。
如果您改为这样做(在 page.evaluate()
的回调函数内)会怎样?
root.a = page.evaluate(function (el, i) {
var element = document.getElementsByClassName('parameterfull')[0];
var children = Array.prototype.slice.call(element.childNodes);
var temp = children.map(function(node) { return node.innerHTML });
for (i = 0; i < temp.length; i++) {
console.log(temp[i])
}
return temp;
});
我正在使用 PhantomJS 抓取一些数据
var root = this;
var a = [];
page.open('https://www.thegioididong.com/dtdd/iphone-x-256gb', function (status) {
page.evaluateAsync(function () {
console.log("click now")
document.getElementsByClassName("viewparameterfull")[0].click()
}, 3000)
setTimeout(function (a, b) {
root.a = page.evaluate(function (el, i) {
console.log("get data now")
var temp = document.getElementsByClassName('parameterfull')[0].childNodes
for (i = 0; i < temp.length; i++) {
console.log(temp[i].innerHTML)
}
//Output html of all childNodes as intended
return temp
})}
, 10000)
})
setTimeout(function () {
console.log("log now");
for (i = 0; i < a.length; i++) {
console.log(a[i].innerHTML)
}
//Output only the first child of a, but a.length still shows 51 (enough number of child nodes)
console.log(a)
}, 20000)
通过子节点到控制台的第一个循环有效 - 它将每个子节点打印到控制台上
但是第二个循环似乎不起作用 - 它只打印第一个值并显示错误 TypeError: null is not an object (evaluating 'a[i].innerHTML')
这里有什么问题?
根据 PhantomJS docs,page.evaluate()
的 return 值必须是 JSON-serializable。我猜 PhantomJS 的 DOM 节点的内部表示不是。
如果您改为这样做(在 page.evaluate()
的回调函数内)会怎样?
root.a = page.evaluate(function (el, i) {
var element = document.getElementsByClassName('parameterfull')[0];
var children = Array.prototype.slice.call(element.childNodes);
var temp = children.map(function(node) { return node.innerHTML });
for (i = 0; i < temp.length; i++) {
console.log(temp[i])
}
return temp;
});