javascriptnode.jspuppeteer

Click on random Google Search result using NodeJS and Puppeteer?


I'm attempting on making a small script to click on a random Google Search result after searching "'what is ' + Word." Nothing I've done has been able to get me the results I want, heck, I can't even get the script to click a single Google Search result!

I've tried doing multiple things here, such as collecting all search results in an array and clicking a random one (didn't collect into an array), clicking an element by partial text (https:// brought no results), and many other solutions that work in Python, but don't work here.

const puppeteer = require('puppeteer');
const searchbar = "#tsf > div:nth-child(2) > div > div.RNNXgb > div >   div.a4bIc > input"



async function gsearch() {
const browser = await puppeteer.launch({headless:false, args:['--no-sandbox', '--disable-setuid-sandbox']});
const page = await browser.newPage();

await page.goto('https://google.com');
 var fs  = require("fs");
var array = fs.readFileSync("words.txt").toString().split('\n');
var random = array[Math.floor(Math.random() * array.length)]
await page.click(searchbar)
await page.keyboard.type("what is " + random);
await page.waitFor(1000);
await page.evaluate(() => {
  let elements = $('LC20lb').toArray();
  for (i = 0; i < elements.length; i++) {
    $(elements[i]).click();


  } 
 })
}

gsearch();

(ignore any indent-inheritant errors, I swear it looks cleaner in VSC)

Expected to click a random search result. End up getting nothing done, maybe an error or two but that's about it.


Solution

  • LC20lb is not html tag and it should be class name for h3 and by using$() are you trying to select elements with jQuery? use document.querySelectorAll() instead.

    const puppeteer = require('puppeteer');
    const fs = require("fs");
    
    async function gsearch() {
      const browser = await puppeteer.launch({
        headless: false,
        args: ['--no-sandbox', '--disable-setuid-sandbox']
      });
      const page = await browser.newPage();
    
      await page.goto('https://google.com');
      var array = fs.readFileSync("words.txt").toString().split('\n');
      var random = array[Math.floor(Math.random() * array.length)];
      // simple selector for search box
      await page.click('[name=q]');
      await page.keyboard.type("what is " + random);
      // you forgot this
      await page.keyboard.press('Enter');
      // wait for search results
      await page.waitForSelector('h3.LC20lb', {timeout: 10000});
      await page.evaluate(() => {
        let elements = document.querySelectorAll('h3.LC20lb')
        // "for loop" will click all element not random
        let randomIndex = Math.floor(Math.random() * elements.length) + 1
        elements[randomIndex].click();
      })
    }