Playwright与NodeJs - 读取CSV并将数据推送到数组中

3
我正在使用 playwright 库进行网络爬虫,并且URL存储在CSV文件中。我尝试读取CSV文件并将URL选择到一个数组中,以便在爬取代码中使用。
这是我编写的代码。
// Support    
const csv = require('csv-parser');
const fs = require('fs');

// Array to store the URL.
var urls = [];
// This prints an empty array.
console.log(urls);

fs.createReadStream('sample.csv')
  .pipe(csv())
  .on('data', (row) => {
    // Trying push the URL in the array
    urls.push(row);

    // This prints the values of URLs
    console.log(urls);
  })
  .on('end', () => {
    console.log('CSV file successfully processed');
  });
// Here I don't see the URLs but an empty array.
console.log("URLS:" + urls);  

在方法“.on('data'”中,值被推入数组并打印到控制台,但是在执行后,当我尝试从数组中获取URL时,它返回一个空数组。

1
变量名在最后的console.log中是大写的,这就是为什么它为空的原因。 - user3170450
我尝试了所有的方法,但结果仍然是相同的。还有其他建议吗? - Divesh Kumar
2个回答

2
这篇答案假设你的CSV文件中只有链接。
const { test } = require('@playwright/test');
const fs = require("fs");

// Reads the CSV file and saves it  
var links = fs.readFileSync('Path/to/csv')
    .toString() // convert Buffer to string
    .split('\n') // split string to lines
    .map(e => e.trim()) // remove white spaces for each line

// Start of for loop, to loop through csv file
for (const link of links) {
    // Normal test set up for playwright. adding the + link.toString to avoid duplicate test name error
    test('test for ' + link.toString(), async ({ page }) => {
        // First csv file item sent to console
        console.log(link);
        // Goes to that csv link item
        await page.goto(link);
        // Do whatever else you need
    });
}

你的回答可以通过添加更多有关代码的信息以及如何帮助OP来改进。 - Tyler2P
已编辑。希望这足够了解。谢谢。 - JOGO

0
以下代码将从CSV文件中提取数据并存储在一个字符串数组中。然后我们可以使用ArrayName[1]ArrayName[2]来获取实际的值。
const csv = require('csv-parser');
const fs = require('fs');

// Array to store the csv values.
var kpis : string[] = [];

kpis= fs.readFileSync('C:/Users/Public/Documents/KPIValues.csv')
  .toString() // convert Buffer to string
  .split('\n') // split string to lines
  .map(e => e.trim()) ; // remove white spaces for each line;

console.log("All Data:" + kpis);
console.log("First row:"+ kpis[1]);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接