【问题标题】:How to store Javascript data in CSV file如何将 Javascript 数据存储在 CSV 文件中
【发布时间】:2016-12-30 09:59:42
【问题描述】:

我正在使用 PhantomJs 库获取数据

var page = require('webpage').create();
console.log('The default user agent is ' + page.settings.userAgent);
page.settings.userAgent = 'SpecialAgent';
page.open('https://www.apwagner.com/appliance-part/wpl/wp661600', function(status) {
  if (status !== 'success') {
    console.log('Unable to access network');
  } else {
    var ua = page.evaluate(function() {
      return document.getElementById('ModelList').textContent;  
      //return document.getElementById('ModelList').innerHTML; 
    });
    console.log(ua);
  }
  phantom.exit();
});

输出

             1DNET3205TQ0
             7MMMS0100VW0
             7MMMS0100VW1
             7MMMS0120VM0
             7MMMS0140VW0
             7MMMS0160VW0

如果我尝试使用 innerHTML 获取输出,则输出类似于

    <ul class="modelnos">
                        <li><a class="cursor" href="/appliance/1dnet3205tq0" onclick="return ProductService.SaveLogModelView('1DNET3205TQ0', 'MAC')"> 1DNET3205TQ0</a></li>
                        <li><a class="cursor" href="/appliance/7mmms0100vw0" onclick="return ProductService.SaveLogModelView('7MMMS0100VW0', 'MAC')"> 7MMMS0100VW0</a></li>
                        <li><a class="cursor" href="/appliance/7mmms0100vw1" onclick="return ProductService.SaveLogModelView('7MMMS0100VW1', 'MAC')"> 7MMMS0100VW1</a></li>
                        <li><a class="cursor" href="/appliance/7mmms0120vm0" onclick="return ProductService.SaveLogModelView('7MMMS0120VM0', 'MAC')"> 7MMMS0120VM0</a></li>
                        <li><a class="cursor" href="/appliance/7mmms0140vw0" onclick="return ProductService.SaveLogModelView('7MMMS0140VW0', 'MAC')"> 7MMMS0140VW0</a></li>
</ul>

但是作为变量的输出,我想要这个数组格式的输出。

点赞var models = ["1DNET3205TQ0", "7MMMS0100VW0", "7MMMS0100VW1"];

并将此数组放入 csv 文件中。

我怎样才能在数组中获取这些数据并放入 csv。

更新:

实际上,我想从该数组中的每个值创建表 html。

就像表格中的 3 列一样。

<table>
<tr><td> 1DNET3205TQ0 </td>
<td> 7MMMS0100VW0 </td>
<td> 7MMMS0100VW1 </td>
</tr>
<tr><td> 7MMMS0120VM0 </td>
<td> 7MMMS0140VW0 </td>
<td> 7MMMS0160VW0 </td>
</tr>
</table>

【问题讨论】:

  • 对于第一部分,您可以将值推送到数组中,而不是 console.log(ua)
  • 尝试split()函数创建数组。 ua.split('\n')ua.split(' ') 取决于字符串中的分隔符。它将返回一个数组
  • 如何将这些数据推送到数组中。这些数据一次性打印出来
  • @abhishekkannojia anu 请检查有问题的更新

标签: javascript php csv web-scraping


【解决方案1】:

结合使用split()函数和join()函数可以得到正确的结果..(详细解释见代码内comments

cmets 显示在 grey 中,并在其周围有 /**/

/* create a new array for  ua values */

var my_array = [];

var page = require('webpage').create();
console.log('The default user agent is ' + page.settings.userAgent);
page.settings.userAgent = 'SpecialAgent';
page.open('https://www.apwagner.com/appliance-part/wpl/wp661600', function(status) {
  if (status !== 'success') {
    console.log('Unable to access network');
  } else {
    var ua = page.evaluate(function() {
      return document.getElementById('ModelList').textContent;
      //return document.getElementById('ModelList').innerHTML; 
    });
    console.log(ua);

    /*  split    ua   to an array */
    my_array = ua.split(/\s+/);
  }
  phantom.exit();
});

/* now at the end to make into a 'csv' use join() */
/*  the ',' parameter specifies what character to put      in between the values */

var csv_array = my_array.join(",");
console.log(csv_array);

复制步骤:

  1. 使用var my_array = [];创建一个变量来存储值

  2. 在您的函数中,使用my_array.split(/\s+/); 将使用regular expression 将结果拆分为一个数组以匹配whitespace

  3. 循环结束后,使用my_array.join(","); 将所有值组合成一个字符串,并在每个值之间添加一个“,”

编辑

要将结果做成表格,而不是使用my_array.join(),使用for循环,每次循环通过时,必须将grab的数组值与my_array[i]对应,其中i代表数组的索引,然后使用document.createElement()创建各种tabletrtd元素,最后使用appendChild()将元素插入到适当的父元素中以创建表

在示例中,我添加了一个目标 div,表格也将添加到该 div 中

/* original array from other snippet */
var my_array = ["value 1", "value 2", "value 3"];

/* new table element */
var new_table = document.createElement("table");

/*  for loop which sets i to a value for each value listed in my_array */
for (var i = 0; i < my_array.length; i++) {

  /* create a row */
  var new_row = document.createElement("tr");

  /* create a cell for that row */
  var new_cell = document.createElement("td");

  /* set the text in the created cell */
  new_cell.innerText = my_array[i];

  /* add the cell to the row */
  new_row.appendChild(new_cell);

  /* add the row to the table */
  new_table.appendChild(new_row);

}
/* destination div */
var destination = document.getElementById("table_destination");

/* add the table to the destination div */
destination.appendChild(new_table);
#table_destination > table,
td {
  width: 50%;
  border: 1px solid black;
}
&lt;div id="table_destination"&gt;&lt;/div&gt;

【讨论】:

  • push() 用于将单个值放入数组中,它不会创建值数组。你需要split()
  • 我刚刚更新了我的答案以考虑到@anu 所说的内容
  • 另外,它不一定是空格,它可以是换行符作为分隔符。所以如果空格不起作用,你需要尝试split('\n')
  • @anu 实际上split(/\s+/) 匹配换行符空格stackoverflow.com/questions/25218677/…
  • 好我坏
【解决方案2】:
var array = [];
var page = require('webpage').create();
console.log('The default user agent is ' + page.settings.userAgent);
page.settings.userAgent = 'SpecialAgent';
page.open('https://www.apwagner.com/appliance-part/wpl/wp661600', function(status) {
    if (status !== 'success') {
        console.log('Unable to access network');
    } else {
        var ua = page.evaluate(function() {
            return document.getElementById('ModelList').textContent;
        });
        console.log(ua);
        array = ua.split(/\s+/);
    }
    phantom.exit();
});

var fs = require('fs');
//for users running with node
/*fs.writeFile("/home/data.csv", array.join(','), function(err) {
    if(err) {
        return console.log(err);
    }

    console.log("The file was saved!");
});*/
//for users running with phantomjs
fs.write('/home/data.csv', array.join(','), 'w');

【讨论】:

  • 文件未在该位置创建。收到错误TypeError: undefined is not a function (evaluating 'fs.writeFile')
  • 您正在使用nodephantomjs 执行此操作。如果phantomjs 则请使用fs.write(path, content, 'w') 代替fs.writeFile
  • 您能否简单地创建一个包含该变量ua 的数组,以便我可以从该数组创建表。
  • 你想存储在 csv 文件中还是你想创建一个 html 表?变量array 包含数组中的所有值,您可以对其进行迭代
  • 上述解决方案在打开 csv 文件时无法像某些编码错误一样工作。我想要一个可以放在 csv 文件中的 html 表格格式
猜你喜欢
  • 2015-08-24
  • 1970-01-01
  • 1970-01-01
  • 2019-01-24
  • 2019-03-03
  • 1970-01-01
  • 2021-05-21
  • 1970-01-01
  • 2022-01-20
相关资源
最近更新 更多