【发布时间】: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