Click anywhere on page using Puppeteer

Viewed 1256

Currently I'm using Puppeteer to fetch cookies & headers from a page, however it's using a bot prevention system which is only bypassed when clicking on the page; I don't want to keep this sequential so it's "detectable"

How can I have my Puppeteer click anywhere on the page at random? regardless of wether it clicks a link, button etc..

I've currently got this code

const getCookies = async (state) => {
    try {
        state.browser = await launch_browser(state);
        state.context = await state.browser.createIncognitoBrowserContext();
        state.page = await state.context.newPage();
        await state.page.authenticate({
            username: proxies.username(),
            password: proxies.password(),
        });
        await state.page.setViewport(functions.get_viewport());
        state.page.on('response', response => handle_response(response, state));
        await state.page.goto('https://www.website.com', {
            waitUntil: 'networkidle0',
        });
        await state.page.waitFor('.unlockLink a', {
            timeout: 5000
        });
        await state.page.click('.unlockLink a');
        await state.page.waitFor('input[id="nondevice"]', {
            timeout: 5000
        });
        state.publicIpv4Address = await state.page.evaluate(() => {
            return sessionStorage.getItem("publicIpv4Address");
        });
        state.csrfToken = await state.page.evaluate(() => {
            return sessionStorage.getItem("csrf-token");
        });
        //I NEED TO CLICK HERE! CAN BE WHITESPACE, LINK, IMAGE
        state.browser_cookies = await state.page.cookies();
        state.browser.close();
        for (const cookie of state.browser_cookies) {
            if(cookie.name === "dtPC") {
                state.dtpc = cookie.value;
            }
            await state.jar.setCookie(
                `${cookie.name}=${cookie.value}`,
                'https://www.website.com'
            )
        }
        return state;
    } catch(error) {
        if(state.browser) {
            state.browser.close();
        }
        throw new Error(error);
    }
};
1 Answers

The simplest way I can think of out of my head to choose a random element from DOM would be probably something like using querySelectorAll() which will return you an array of all <div>s in your document (or choose any other element, like <p> or anything else), then you can easily use click() on random one from the result, for example:

await page.evaluate(() => {
  const allDivs = document.querySelectorAll('.left-sidebar-toggle');
  const randomElement = allDivs[Math.floor(Math.random() * allDivs.length)];
  randomElement.click();
});
Related