javascript - 如何为返回表中的每一行添加换行符?

标签 javascript node.js web-scraping fs nightmare

我正在使用网络抓取工具并成功打印了一张表格,但表格的格式很糟糕。

我已经尝试过一些事情了

1) const people = [...peopleList].map(personEntry => personEntry.innerText + '\n")

2) const people = [...peopleList].map(personEntry => personEntry.innerText).join("\n")

3)  .then(result => fs.writeFile('testfile.csv',JSON.stringify(result + "\n"),'utf8', function(err) {

我很困惑,我认为解决方案可能涉及一个循环并附加它,但我不是 100% 肯定。

const Nightmare = require('nightmare')
const nightmare = Nightmare({ show: false  })
const fs = require('fs');


nightmare
  .goto('https://www.google.com/')
  .type('#lst-ib', 'datatables')
  .click('input[value= "Google Search"]')
  .click('.rc >.r > a')
  .select('select[name="example_length"]',"100")


  .evaluate(function() {
    const headerFields = document.querySelectorAll("#example thead tr th")
    const peopleList = document.querySelectorAll("#example tbody tr");
    const people = [...peopleList].map(personEntry => personEntry.innerText)
    const header = [...headerFields].map(headerEntry => headerEntry.innerText)

    return {
      log: header,
      list: people
    }
  })

  .end()

  .then(result => fs.writeFile('testfile.csv',JSON.stringify(result),'utf8', function(err) {
    if (err) {
      console.log('File not saved or corrupt');
    } else {
      console.log('your file is saved')
    }
  }))
  .catch(error =>{
    console.error('fail')
  })

*Update 如果我在 CSV 预览器中打开文件,这就是我所看到的。我想要姓名、职位、办公室、年龄、开始日期、薪水在一行,然后所有返回的人(带有他们的名字办公室等)返回他们自己的一行。

shows all elements on the same row What the csv looks like right now 有什么想法吗?

最佳答案

这段代码中发生了一些不正确的解析和字符串操作,但这是一个非常简单的修复:

const Nightmare = require('nightmare')
const nightmare = Nightmare({ show: true })
const fs = require('fs');


nightmare
  .goto('https://www.google.com')
  .type('#lst-ib', 'datatables')
  .click('input[value= "Google Search"]')
  .click('.rc >.r > a')
  .select('select[name="example_length"]', "100")

  .evaluate(function () {
    const headerFields = document.querySelectorAll("#example thead tr th")
    const peopleList = document.querySelectorAll("#example tbody tr")

    const people = Array
      .from(peopleList)
      .map(entry => entry
        .innerText
        .replace(/\t/g, ',')
      )
    const header = Array
      .from(headerFields)
      .map(headerEntry => headerEntry
        .innerText
      )
      .join(',')

    return ([])
      .concat(header, people)
      .join('\n')
  })

  .end()

  .then(result => fs.writeFile(
      './testfile.csv',
      result,
      'utf8',
      function (err) {
        if (err) throw err;
        console.log('your file is saved')
      }
    )
  )
  .catch((err) => {
    console.error(err)
  });

首先,我们将错误处理程序更改为一个更真实的示例,每次都会将我们抛出到相同的 .catch 语句,并且可以接受调试器中断。

接下来我们更改写入文件以写入原始字符串,这样它实际上会输出 CSV,而不是 JSON 字符串(这将导致所有内容都在同一行)

最后,我们更改评估回调以将 nodeList(s) 转换为数组,然后进行转换,并最终用换行符将它们全部连接起来。

您可能遇到的唯一问题是计时问题,因此一些等待语句可能正是您想要的。

关于javascript - 如何为返回表中的每一行添加换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51485310/

相关文章:

r - 使用 R 进行网页抓取和循环浏览页面

javascript - 如何使用ref获取所有列表项?

javascript - 关于node.js回调中的 'this'

python - 在 VPS 上运行 Selenium webdriver 时出现各种 Urllib2 错误

node.js - socket.io - 如何在命名空间上广播消息?

c - 从 Node.js 访问 C 函数

python - 使用动态鼠标悬停事件抓取网站

javascript - 迭代 Angular 4 Firebase 数据库中的对象数组

javascript - 用 Twitter Bootstrap 的模式替换标准的 javascript 确认 - 谁触发了它?

javascript - 从 jQuery .click 增加一个变量