将Casper JavaScript数据插入CSV文件 [英] Insert casper javascript data to CSV file
问题描述
我想将数据从Casper JS传递到我当前正在使用的CSV文件中
I want to pass data from casper JS to CSV file I am currently using
fs = require('fs');
fs.write('test.csv', "name, title", "a");
fs.write('test.csv', name.trim()+","+title.trim(), "a");
这是一个循环,所以有很多记录
this is inside a loop so there are many records
但是打印到CSV文件不会插入新行.目前它是这样写的,我只想要2列
but printing to the CSV file is not inserting to a new row. It currently writes like this and I only want 2 columns on this
Name Title
name1 name1 name2 title2 name3 title3
推荐答案
添加换行符
fs.write('test.csv', name.trim()+","+title.trim()+"\n", "a");
CSV有所不同,但通常都包含四个特殊字符,
CSVs vary, but all usually have four special chars,
- 定界符(逗号)
- 转义字符(通常为
\
,用于在数据中转义其他特殊字符 - 行定界符(通常为
\n
,换行符) - 包装器,(通常用引号引起来的每个值)
- delimiter (the comma)
- escape char (usually
\
, use to escape the other special chars when used in the data - line delimiter (usually
\n
, the newline character), - wrapper, (usually quotes that wrap around each value)
因此,如果您真的想要适当的CSV,则可以执行以下操作.
So, if you really want a proper CSV you would do something like this.
function escapeCSVData(text){
text = text.
replace("\", "\\,"). // escape any escape chars
replace(",", "\,"); // escape commas
return '"'+text+'"'; // add quotes
}
fs.write('test.csv', escapeCSVData(name.trim())+","+escapeCSVData(title.trim())+"\n", "a");
我没有测试上面的内容,但这应该对您有用.
I didn't test the above, but that should work for you.
编辑
我刚刚了解到逗号只是用引号引起来,而不是转义,因此该函数实际上看起来像这样.
I just learned that commas are simply quoted, not escaped, so the function would actaully just look like this..
function escapeCSVData(text){
return '"'+text+'"'; // add quotes
}
这篇关于将Casper JavaScript数据插入CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!