【问题标题】:Playwright & NodeJs - Read CSV and push data to an arrayPlaywright & NodeJs - 读取 CSV 并将数据推送到数组
【发布时间】:2026-02-11 17:50:01
【问题描述】:

我正在使用 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 时,执行后它返回一个空数组。

【问题讨论】:

  • 变量名是大写的,你在最后执行 console.log。这就是为什么它是空的。
  • 我尝试了所有方法,但是结果还是一样。还有其他推荐吗?

标签: javascript node.js arrays web-scraping playwright


【解决方案1】:

这个答案是假设你的 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 的更多信息来改进。
  • 已编辑。希望这是足够的信息。谢谢