nightmarejs用querySelectorAll刮取多个元素

我试图从一个instagram的个人资料页面用nightmarejs(使用电子作为浏览器phantomjs衍生物)刮取一些信息。

目标是获取configuration文件上所有图像的ALT标签(例如,我只关注“显示更多”button之前的图像)

var Nightmare = require('nightmare'); var nightmare = Nightmare({ show: true }); nightmare .goto('https://www.instagram.com/ackerfestival/') .evaluate(function () { let array = [...document.querySelectorAll('._icyx7')]; return array.length; }) .end() .then(function (result) { console.log(result); }) .catch(function (error) { console.error('Search failed:', error); }); 

这个例子工作,数组长度为12.电子浏览器打开和closures,所以一切都很好。 但是,如果我改变返回只是数组,电子浏览器从不closures,我没有得到一个console.log。

我究竟做错了什么? 我想从数组或对象的图像中获取所有信息。

你碰到的问题是document.querySelectorAll()返回一个DOMElementNodeList 。 这两个对象types不能很好地序列化,并且.evaluate()的返回值必须在IPC边界上序列化 – 我打赌你在.evaluate()调用的另一端获得了一个空数组?

这里最简单的答案是从NodeList明确你想要的东西。 从髋关节开始,像下面这样的东西应该能够让人想到:

 .evaluate(function(){ return Array.from(document.querySelectorAll('._icyx7')).map(element => element.innerText); }) .then((innerTexts) => { // ... do something with the inner texts of each element })