Monday, 2 April 2018

How to use conditional statements in puppeteer ?

I hope this is the right place to ask this question because puppeteer is a node library. There are very little tutorials and explanations available about puppeteer so it came to this subreddit In the hopes that someone is more familiar with puppeteer.For practice purposes only I'm trying to make puppeteer go to google.com check if the text of a certain link is "images". And if that is the case, click on the link and take a screenshot.What I'm struggling with is that you can't use regular JavaScript outside the page.evaluate function and you can't use puppeteer methods inside the page.evaluate function right ?As my code is now, the script will take a screenshot regardless of the text of the link. I would like it to only take a screenshot when the if condition is met. but I can't usepage.screenshot({path: 'google.png'}); within the page.evaluate function because it's not JavaScript.If I do this it returns the error "page is not defined" Am I miss understanding something ? How do I solve this ?const puppeteer = require('puppeteer'); async function getPic() { const browser = await puppeteer.launch( { headless: false}); const page = await browser.newPage(); await page.goto('https://google.com'); await page.evaluate(() => { const imageslink = document.querySelector("a[data-pid='2']"); if (imageslink.textContent === "Images") { imageslink.click(); //take screenshot ? } }); await page.screenshot({path: 'google.png'}); await browser.close(); } getPic(); Any help would be greatly appreciated and sorry if this is the wrong place to ask.

Submitted April 02, 2018 at 11:49AM by DutchSparks

No comments:

Post a Comment