【问题标题】:Chrome download error when downloading file with Puppeteer使用 Puppeteer 下载文件时 Chrome 下载错误
【发布时间】:2021-04-14 20:38:08
【问题描述】:

我有一个显示页面的应用程序,用户单击按钮并下载 CSV 文件。我想用 Puppeteer 运行它。

问题是 CSV 下载为空且出现错误。 headless true 和 false 都会发生这种情况。页面加载完毕,我增加了超时,但仍然失败。可能是什么问题?

const puppeteer = require('puppeteer');

(async () => {
    
    const browser = await puppeteer.launch({
       headless: false
    });

    const page = await browser.newPage();
    await page.goto('http://localhost:4400/login', { waitUntil: 'networkidle2' });    
    
    await page._client.send('Page.setDownloadBehavior', {
        behavior: 'allow',
        downloadPath: './',
    });

    await page.waitForSelector('#run-and-export');
    await page.click('#run-and-export');
  
    // file-downloaded is turned on when the file finished downloading (not to close the window)
    await page.waitForSelector('#file-downloaded', { timeout: 120000 }); 

    await browser.close();
    
})();

应用程序中生成要下载的文件的代码是一个 Angular 服务:

@Injectable({ 
    providedIn: 'root' 
})
export class DownloadService {

    downloadFile(content:any, fileName: string, mimeType: string){
    
        var blob = new Blob([(content)], {type: mimeType});
        var a = document.createElement('a');
        a.href = window.URL.createObjectURL(blob);
        a.download = fileName;
        a.click();

    }
}

【问题讨论】:

  • 有没有试过在启动浏览器时设置userDataDir
  • 我刚试了下,同样的错误:const browser = await puppeteer.launch({ headless: false, userDataDir: './myUserDataDir' });
  • 您正在丢弃所有可能包含有关正在发生的事情的线索的错误。确保将catch 附加到主异步函数。
  • 我将主异步函数包装为 f() 并添加了 f().catch((error) => console.log('there\'s an error=' + error)) 并且没有打印任何内容

标签: javascript node.js puppeteer google-chrome-headless


【解决方案1】:

这就是它成功的原因:

const downloadPath = path.resolve('/my/path');

await page._client.send('Page.setDownloadBehavior', {
    behavior: 'allow',
    downloadPath: downloadPath 
});

【讨论】:

    【解决方案2】:

    我遇到了同样的问题,下载失败,在下载目录中我得到了filename.pdf.crdownload,没有其他文件。

    下载目录比应用目录../../download_dir高两级

    解决方案是(根据 ps0604 的建议):

    const path = require('path');
    const download_path = path.resolve('../../download_dir/');
    
    await page._client.send('Page.setDownloadBehavior', {
        behavior: 'allow',
        userDataDir: './',
        downloadPath: download_path,
    });
    

    如果有人在搜索.crdownload 文件并下载错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-24
      • 2011-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多