I am trying to create a puppeteer script to download a PDF file. I feel like I'm totally over complicating this! Here's an example of what I want to automate:
- Go to https://www.espn.com/sports-betting/story/_/id/35852378/2023-ncaa-men-tournament-march-madness-printable-brackets-college-basketball
- Click on the text/link "NCAA Tournament Printable Bracket". The document loads in the Chrome PDF window.
- Save the PDF file.
EDIT: I should have mentioned that the file is generated after clicking a button so I cannot use a specific link and download that file.
I have tried the following:
- Using the .pdf function. This prints a PDF of the print view.
- Pressing Cmd + A. This isn't supported by Chrome with Mac it looks like because it's a native function.
- Tabbing to the save button and pressing the enter button. This doesn't work because the Mac save modal isn't visible to puppeteer.
const puppeteer = require('puppeteer');
async function run() {
// const browser = await puppeteer.launch();
const browser = await puppeteer.launch({
headless: false
});
const page = await browser.newPage();
await page.goto('https://www.espn.com/sports-betting/story/_/id/35852378/2023-ncaa-men-tournament-march-madness-printable-brackets-college-basketball');
const html = await page.content();
await page.waitForSelector('#article-feed > article:nth-child(1) > div > div.article-body > ul > li:nth-child(1) > p > a > em > strong');
// Print and save test 1
await page.pdf({
path: 'bracket.pdf',
format: 'A4'
});
// Print and save test 2
await page.keyboard.press('Tab');
await page.keyboard.press('Tab');
await page.keyboard.press('Tab');
await page.keyboard.press('Tab');
await page.keyboard.press('Tab');
await page.keyboard.press('Tab');
await page.keyboard.press('Tab');
await page.keyboard.press('Tab');
await page.keyboard.press('Enter');
await page.keyboard.press('Enter');
// Print and save test 3
await page.evaluate(() => {
window.print = function() {};
});
// Print and save test 4
await page.keyboard.down('Cmd');
await page.keyboard.down('S');
await page.keyboard.up('S');
await page.keyboard.up('Cmd');
await page.waitForTimeout(5000);
await page.keyboard.up('Enter');
await browser.close();
}
run();