LinkedIn Auto Connection Request using Puppeteer

Viewed 36

I wrote JS code to build auto connection requests to any profile. Using a puppeteer, I am able to go to a particular profile. After that, I would like to press the "Connect" button programmatically.

When I am doing it in the browser console. I am able to do it (by accessing the button using its class name and then using the click() function)

However when I am trying to do it in the JS file, somehow, the puppeteer is not returning me button elements.

I am sharing the codes of the JS File. And also have screenshots of errors I am getting using puppeteer.

const puppeteer = require("puppeteer");

(async () => {
  //launch a chrome browser
  const browser = await puppeteer.launch({
    headless: false,
    executablePath:
      "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
    defaultViewport: null,

    slowMo: 250,
  });

  //open a new page on browser
  const page = await browser.newPage();

  //setting Linkedin session cookie for me login on Linkedin
  await page.setCookie({
    name: "li_at",
    value:
      "AQEDATKQWLoA3BXSAAABgxjkkiIAAAGDPPEWIlYAAk6VuqqA04hXPdHVfcd5N2sWI5edFWwbhuk1a_4ewbaLdL-qObKsttP2cxO4TJ2zeuVLiweY6aBzGFQb9CCOLRLhIAsNrTigGX4K0Q9Kls_hIMnL",
    domain: ".www.linkedin.com",
  });

  //Take to a particular profile URL
  await page.goto("https://www.linkedin.com/in/alefiya-singaporewala/");

  //suppose to return button elements with className given. Same command from 
// document.getElementsByClassName....works in browser console but not working here

  const buttons = await page.evaluateHandle(() => {
    document.getElementsByClassName(
      "artdeco-button artdeco-button--2 artdeco-button--primary ember-view pvs-profile-actions__action"
    );
  });

  //click button

  await buttons[0].click();

  //close browser connection

  setTimeout(async () => {
    await browser.close();
  }, 500000);
})();

Error showing buttons object null

1 Answers

I found the solution, following code works for my case (using simply page.$$ function):

await page.waitForSelector(
    '[class="artdeco-button artdeco-button--2 artdeco-button--primary ember-view pvs-profile-actions__action"]'
  );
  const buttons = await page.$$(
    '[class="artdeco-button artdeco-button--2 artdeco-button--primary ember-view pvs-profile-actions__action"]'
  );

  console.log("buttons", buttons);
\\Connect button is the 2nd element in the array
  await buttons[1].click(); 
Related