[英]nightmarejs scrape multiple Elements with querySelectorAll
我正在嘗試使用nightmarejs(使用電子作為瀏覽器的phantomjs派生詞)從Instagram個人資料頁面中搜索一些信息。
目標是獲取配置文件中所有圖像的alt標簽(例如,我只關注“顯示更多”按鈕之前的圖像)
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.電子瀏覽器打開和關閉,所以一切都很好。 但是,如果我將返回更改為只是數組,電子瀏覽器永遠不會關閉,我沒有得到console.log。
我究竟做錯了什么? 我想從數組或對象中的圖像中獲取所有信息。
你遇到的問題是document.querySelectorAll()
返回DOMElement
的NodeList
。 這兩個對象類型沒有很好地序列化,並且.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
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.