【问题标题】:How to report the scraping progress of X-Ray?如何上报 X-Ray 的抓取进度?
【发布时间】:2018-09-12 16:09:49
【问题描述】:

就像我用下面的代码刮了 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')

【问题讨论】:

  • 您说“.then”似乎不起作用-您是如何测试它的?在其中添加一个 console.log 看看会发生什么,例如 .then((res) => { console.log(res) }) 等
  • 我得到了他的错误:TypeError: x(...).limit(...).paginate(...).write(...).then is not a function跨度>

标签: javascript x-ray


【解决方案1】:

.then() 可以工作,但写后不行

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

您可以尝试删除 .write 并使用 then 来控制台记录结果,如下所示:

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
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-18
    • 1970-01-01
    相关资源
    最近更新 更多