0

就像我用下面的代码刮了 3 页:

var Xray = require('x-ray');
var x = Xray();

x('https://blog.ycombinator.com/', '.post', [{
  title: 'h1 a',
  link: '.article-title@href'
}])
  .paginate('.nav-previous a@href')
  .limit(3)
  .write('results.json')

我如何报告进度?

我尝试了 .then() 但似乎不起作用。

x('https://blog.ycombinator.com/', '.post', [{
  title: 'h1 a',
  link: '.article-title@href'
}])
  .paginate('.nav-previous a@href')
  .limit(3)
  .write('results.json')
  .then(
  //something to report the progression
  )

或同样不起作用的回调函数

x('https://blog.ycombinator.com/', '.post', [{
  title: 'h1 a',
  link: '.article-title@href'
}])(()=>{
  //something to report the progress
  })
  .paginate('.nav-previous a@href')
  .limit(3)
  .write('results.json')
4

1 回答 1

1

.then() 可以工作,但不能在写入之后

.then() 期望(我认为!)一个承诺。在 .write() 之后什么都没有了。

您可以尝试删除 .write 并使用 then 来 console.log 这样的结果:

var Xray = require('x-ray');
var x = Xray();

x('https://blog.ycombinator.com/', '.post', [{
  title: 'h1 a',
  link: '.article-title@href'
}])
  .paginate('.nav-previous a@href')
  .limit(3)
/*   .write('results.json') */
  .then(result => {
  })

这将打印您抓取的页面的标题和链接。

您可以使用 .then() 并在内部使用 fs 之类的东西将每个结果打印到文件中,例如

var Xray = require('x-ray');
const fs = require('fs')
var x = Xray();



x('https://blog.ycombinator.com/', '.post', [{
  title: 'h1 a',
  link: '.article-title@href'
}])
  .paginate('.nav-previous a@href')
  .limit(3)
  .then(results => {
    console.log(results)

    let res = JSON.stringify(results, null, 2);

    fs.writeFile('results.json', res, (err) => {
      if (err) throw err

      console.log('result saved!')
    })
  })

这里 JSON.stringify(results, null, 2) 只是获取一个对象(results 是一个对象数组)并将其转换为 json (第三个参数 - that 2 - 只是为了让它漂亮)

然后使用 fs.writeFile (本机节点模块)在 results.json 上编写 json 对象

你甚至可以使用 forEach() 逐个对象

喜欢

 results.forEach(result => {
 //log the individual result and put in on an empty array, and then write the array
})
于 2018-09-27T01:46:57.330 回答