csv - 如何使用 javascript apify puppeteer 从谷歌趋势下载 Csv
问题描述
我使用该代码使用 apify js 从谷歌趋势下载 csv,但它不起作用,你能帮我吗?结果是一个内容错误的 csv。我尝试从谷歌趋势中获取所有 csv。
const path = require('path');
const downloadPath1 = path.resolve(__dirname, './downloads');
const fs = require('fs');
try{
const util = require('util');
await util.promisify(fs.mkdir)(downloadPath1);
}
catch( e){
}
await page.setRequestInterception(true);
//await page.click(csvSelector);
await page.waitForSelector(csvSelector)
const hrefElement = await page.$(csvSelector);
await hrefElement.click();
const xRequest = await new Promise(resolve => {
page.on('request', async interceptedRequest => {
const type = interceptedRequest.resourceType();
log.info(type)
if ( type == "xhr" ) {interceptedRequest.abort();
resolve(interceptedRequest);}
else interceptedRequest.continue();
});
});
log.info(xRequest._url);
const request = require('request-promise');
const options = {
encoding: null,
method: xRequest._method,
uri: xRequest._url,
body: xRequest._postData,
headers: xRequest._headers
}
/* add the cookies */
const cookies = await page.cookies();
options.headers.Cookie = cookies.map(ck => ck.name + '=' + ck.value).join(';');
const response = await request(options);
fs.writeFileSync(downloadPath1+'/binary.csv', response);
const fileObjs = fs.readdirSync(downloadPath1, { withFileTypes: true });
console.log("\nCurrent directory files:");
fileObjs.forEach(file => {
console.log(file);
});
// There won't be more files so let's pick the first
const fileData = fs.readFileSync(downloadPath1+`/${fileObjs[0].name}`);
log.info(fileData);
// Now we can use the data or save it into Key-value store.
await Apify.setValue('MY-Csv.csv', fileData, { contentType: 'application/csv'});
我希望有人可以为此提出解决方案谢谢
解决方案
推荐阅读
- delphi - 如何从 DLL 内部访问 DLL 中的图像?
- javascript - 简单的反应错误:不能在 Next.js 中使用 @material-ui/picker 库
- javascript - 如何在nodejs中使用弹性搜索聚合查询进行分页(从,大小)
- java - 访问 JavaFX SceneBuilder 应用程序中的字段
- ubuntu - 如何在 Ubuntu 上的 Visual Studio Code 中运行 Scheme?
- html - 我想使用 nodejs 在 mogodb 上保存 json 文件
- javascript - 在 React Hook 表单中进行验证以确保至少选中一个复选框?
- spring-boot - Camel restConfiguration 将主机设置为路由的值
- ios - 如何在 PreviewProvider 的一个视图中为该视图使用设置的变量?
- arrays - 虽然循环和数组导致非常奇怪的行为......可能是内存混淆