[英]How can I add a line break to each row in my returned table?
我正在使用Web scraper和一個表成功打印,但表的格式很糟糕。
我以前嘗過一些東西
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預覽器中打開文件,則更新 ,這就是我所看到的。 我希望姓名,職位,辦公室,年齡,開始日期,工資在一行,然后所有返回的人(與他們的姓名辦公室等)返回他們自己的行。
在此代碼中發生了一些不正確的解析和字符串操作,但這是一個非常簡單的修復:
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字符串(這將導致所有內容都在同一行)
最后,我們更改了evaluate回調,將nodeList(s)轉換為Array,然后轉換,最后將它們全部加入換行符。
您可能遇到的唯一問題是計時問題,因此一些等待語句可能正是您想要的。
也許嘗試模板文字,這似乎適用於這個短循環。 在您的情況下,您可能想嘗試:
const people = [...peopleList].map(personEntry => {`${personEntry.innerText} \\n`})
示例循環:
for (var i=0; i<5; i++){ console.log(`This is ${i} times through \\n More Text On Next Line`) }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.