【发布时间】:2018-07-23 18:40:25
【问题描述】:
我正在开发一个网络抓取工具,并且成功打印了一个表格,但是表格的格式很糟糕。
我之前尝试过一些东西
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')
})
*更新如果我在 CSV 预览器中打开文件,这就是我所看到的。我想要一行中的姓名、职位、办公室、年龄、开始日期、薪水,然后所有返回的人(以及他们的姓名办公室等)都返回他们自己的行。
【问题讨论】:
-
你能显示
peopleList的样本值吗? -
@JeremyLee 我现在添加了 csv 的样子,我将使用正则表达式来修复它的外观,但我很困惑为什么它不会将每个人添加到自己的行中)但是一个返回值当前可能是
Name | Position | Office | Age | Start Date | Salary Airi Satou Accountant Tokyo 33 2008/11/18 60,000,它们应该在一个数组中,如下面的[airi,accountant,tokyo,33,2008/11/18,60000] -
所以它看起来像是一个制表符分隔值表。在这种情况下,您可以将
\t替换为,,然后将.join全部替换为\n -
哦,我想我遇到了问题,因为它以前是一个节点列表,我使用扩展运算符来转换它 - 所以我应该映射节点列表!谢谢!
-
啊,如果它返回的是节点列表而不是数组,那么您可能需要传播
标签: javascript node.js web-scraping fs nightmare