我正在運行一個nightmare.js腳本,我試圖抓取頁面上多個元素的截圖。Nightmare.js截圖緩衝區長度0
第一個元素被捕獲得很好,但是在摺疊下面的每個其他元素都是以零長度捕獲的。我正在努力調試這個問題。任何幫助將不勝感激。
基本上,此腳本遍歷頁面並選擇全部頁面上與選擇器匹配的元素。然後,使用async
它收集響應並返回對象的緩衝區。問題是摺疊下面的元素沒有被截圖(緩衝區長度最終爲零)。我試圖wait()
並滾動到元素,但我還沒有取得任何成功。
import * as Nightmare from 'nightmare'
import * as vo from 'vo'
import * as async from 'async'
import * as fs from 'fs'
const urls:String[] = [
'https://yahoo.com/'
]
Nightmare.action('snap', function(selector:String, done:Function) {
const self = this;
this.evaluate_now(function (selector) {
return Array.from(document.querySelectorAll(selector))
.map((ele:Element) => {
if (ele) {
const rect = ele.getBoundingClientRect()
const r:Function = Math.round
return {
x: r(rect.left),
y: r(rect.top),
width: r(rect.width),
height: r(rect.height)
}
}
})
}, function(err, clips) {
if (err) return done(err)
if (!clips) return done(new Error(`Selector not found`))
let snaps = []
const snap = (clip, cb) => {
self
.scrollTo(clip.y - clip.height, clip.x)
.screenshot(clip, cb)
.run()
}
async.mapSeries(clips.reverse(), snap, (err, res) => {
done(err, res)
})
}, selector)
})
const scrape = (url) => {
const nightmare = Nightmare({
show: true
});
nightmare
.goto(url)
.snap('.navbar')
.end()
.then((buffers:Buffer[]) => {
buffers.forEach((data, index) => {
fs.writeFileSync(`images/navbar-${index}.png`, data)
})
})
}
urls.forEach(scrape)
我想重現這個問題,但我發現yahoo.com網頁上沒有這樣的元素「.navbar」。你能澄清一下嗎?當然,Evgeny, –
。試用一個帶有bootstrap的頁面,例如:https://getbootstrap.com/ – auser
您是否可以複製它,@EvgenySorokin? – auser