我正在运行一个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