我正在运行一个nightmare.js脚本,试图在页面上截取多个元素的屏幕截图。第一个元素可以成功地捕捉,但是所有其他在折叠下方的元素的长度都为零。我正在努力调试这个问题。任何帮助都将不胜感激。
基本上,该脚本遍历页面并选择与选择器匹配的所有元素。然后,使用异步调用收集响应并返回对象缓冲区。问题是折叠下方的元素没有被拍摄(缓冲区的长度最终为零)。我尝试使用wait()和滚动到元素,但还没有成功。
基本上,该脚本遍历页面并选择与选择器匹配的所有元素。然后,使用异步调用收集响应并返回对象缓冲区。问题是折叠下方的元素没有被拍摄(缓冲区的长度最终为零)。我尝试使用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)