Reputation: 2141
I am using Puppeteer and given a list of topics with the same tag structure I need to click a random one. If I use document.querySelector and click a random topic it works but I am not sure I can use page.evaluate because later on I need to repeat the click again and make sure the previous topic.
The error I am getting is:
UnhandledPromiseRejectionWarning: TypeError: page.$(...).click is not a function
Upon debugging topics array gives me an ElementHandle array and the randomNumber is -1.
My code is this:
await page.waitForSelector('.o-topicselect__list');
// get the all li elements
const topics = await page.$$('.o-topicselect__list li')
// create a random number from 0 to the topics.length-1
const randomNumber = Math.floor(Math.random() * topics.length - 1);
// click a random topic
await page.$(`.o-topicselect__list li:nth-child(${randomNumber}) a`).click()
Any Help is greatly appreciated.
Upvotes: 0
Views: 1126
Reputation: 166
The issue is that you are trying to run .click()
on a promise. You need to first wait for the promise returned by page.$
to resolve to an ElementHandle
, and then you can click it:
let link = await page.$(`.o-topicselect__list li:nth-child(${randomNumber}) a`);
await link.click();
Upvotes: 1