24
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Puppeteerでファイルダウンロード

Last updated at Posted at 2019-01-29

Question: How do I get puppeteer to download a file?

Page.FileDownloadedは今後追加されるみたい

クリックからダウンロードする

const downloadPath = './download';

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

await page.goto('https://www.google.co.jp/chrome/', {waitUntil: 'networkidle0'});
await page.waitForSelector('#js-download-hero');
await page.click('#js-download-hero');
await page.click('#js-accept-install');
let filename = await ((async () => {
  let filename;
  while ( ! filename || filename.endsWith('.crdownload')) {
      filename = fs.readdirSync(downloadPath)[0];
      await sleep(1000);
  }
  return filename
})());

function sleep(milliSeconds) {
  return new Promise((resolve, reject) => {
    setTimeout(resolve, milliSeconds);
  });
}

直接ダウンロードする

page.gotoで直接ファイルを指定すると上手くいかなかったが、クリックからダウンロードする際はうまくいっていたのでこれを利用してみました。無理矢理ダウンロードリンクを作ってクリックしてしまうことでダウンロード出来ました。このページではAjaxでダウンロードしている方法もあったりしました。

Chromeのページに行ってダウンロードするのはVSCodeという暴挙
const downloadPath = './download';

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

await page.goto('https://www.google.co.jp/chrome/', {waitUntil: 'networkidle0'});
await page.evaluate(() => {
  let body = document.querySelector('body');
  body.innerHTML = '<a id="puppeteer" href="https://code.visualstudio.com/docs/?dv=win">VSCode</a>'
});
await page.waitForSelector('#puppeteer');
await page.click('#puppeteer');
let filename = await ((async () => {
  let filename;
  while ( ! filename || filename.endsWith('.crdownload')) {
      filename = fs.readdirSync(downloadPath)[0];
      await sleep(1000);
  }
  return filename
})());

function sleep(milliSeconds) {
  return new Promise((resolve, reject) => {
    setTimeout(resolve, milliSeconds);
  });
}
24
22
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?