-
-
Save motemen/ce4ca5d4134b31a11725f3461a09c136 to your computer and use it in GitHub Desktop.
Example code to download files via browser automation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { chromium } from "playwright"; | |
(async () => { | |
const browser = await chromium.launch(); | |
const page = await browser.newPage(); | |
await page.goto("https://motemen.github.io/beautiful-graph-maker/"); | |
const button = await page.$("button"); | |
if (!button) { | |
throw new Error("not found: button"); | |
} | |
const [download] = await Promise.all([ | |
page.waitForEvent("download"), | |
button.click(), | |
]); | |
// { | |
// path: '/var/folders/hm/0xt2zy.../279506cd-00e1-43d5-ad4f-f72909ba706c', | |
// suggestedFilename: 'graph.png' | |
// } | |
console.log({ | |
path: await download.path(), | |
suggestedFilename: download.suggestedFilename(), | |
}); | |
await browser.close(); | |
})(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import puppeteer from "puppeteer"; | |
import * as path from "path"; | |
const DOWNLOAD_TIMEOUT = 10 * 1000; | |
(async () => { | |
const browser = await puppeteer.launch(); | |
const page = await browser.newPage(); | |
const downloadPath = path.join(process.cwd(), "downloads"); | |
const cdpSession = await page.target().createCDPSession(); | |
await cdpSession.send("Browser.setDownloadBehavior", { | |
behavior: "allow", | |
downloadPath, | |
eventsEnabled: true, | |
}); | |
const downloaded = new Promise<void>((resolve, reject) => { | |
cdpSession.on( | |
"Browser.downloadProgress", | |
(params: { state: "inProgress" | "completed" | "canceled" }) => { | |
if (params.state == "completed") { | |
resolve(); | |
} else if (params.state == "canceled") { | |
reject("download cancelled"); | |
} | |
} | |
); | |
}); | |
await page.goto("https://motemen.github.io/beautiful-graph-maker/"); | |
const button = await page.$("button"); | |
if (!button) { | |
throw new Error("not found: button"); | |
} | |
await button.click(); | |
await Promise.race([ | |
downloaded, | |
new Promise<boolean>((_resolve, reject) => { | |
setTimeout(() => { | |
reject("download timed out"); | |
}, DOWNLOAD_TIMEOUT); | |
}), | |
]); | |
await browser.close(); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment