linkedin webdriver | login linkedin | | Search

The listConnections function is an asynchronous module that retrieves a list of unique LinkedIn connections' URLs by utilizing Selenium to navigate to the user's my network page, check for login status, and retrieve connections until at least 10 unique connections are found. If no driver is provided, it creates a new instance using getClient() and logs in to LinkedIn using loginLinkedIn(), before proceeding with the connection retrieval process.

Cell 1

const fs = require('fs')
const getClient = importer.import("selenium client")
const getAllUntil = importer.import("all elements until")
const loginLinkedIn = importer.import("login linkedin")

async function listConnections(driver) {
  if(!driver) {
    driver = await getClient()
    await loginLinkedIn(driver)
  }

  let url = await driver.getCurrentUrl()
  let loggedIn = url.indexOf('mynetwork') > -1
  if(!loggedIn) {
    await driver.get('https://www.linkedin.com/mynetwork/')
    await new Promise(resolve => setTimeout(resolve, 4000))
  }

  let result = await getAllUntil(driver, 
    false,
    '//a[contains(@href, "/in/")]/@href',
    /* friends */ [],
    (a, b) => a === b,
    (i) => i < 10
  )

  return result.filter((l, i, arr) => arr.indexOf(l) === i)
}

module.exports = listConnections

What the code could have been:

/* eslint-disable no-unused-vars, no-undef, no-prototype-builtins */

import fs from 'fs';
import getClient from './seleniumClient.js';
import getAllUntil from './allElementsUntil.js';
import loginLinkedIn from './loginLinkedIn.js';

/**
 * Retrieves a list of LinkedIn connections.
 *
 * @param {object} driver - The Selenium WebDriver instance.
 * @returns {Promise<string[]>} A list of unique LinkedIn connection URLs.
 */
async function listConnections(driver) {
  // Ensure the driver is initialized and logged in
  if (!driver) {
    driver = await getClient();
    await loginLinkedIn(driver);
  }

  // Navigate to the LinkedIn My Network page
  const url = await driver.getCurrentUrl();
  const isLoggedIn = url.indexOf('mynetwork') > -1;
  if (!isLoggedIn) {
    await driver.get('https://www.linkedin.com/mynetwork/');
    // Introduce a 4-second wait to allow the page to load
    await new Promise((resolve) => setTimeout(resolve, 4000));
  }

  // Retrieve a list of connections using a custom XPath expression
  const connections = await getAllUntil(driver, {
    locateBy: '//a[contains(@href, "/in/")]/@href',
    ignoreDuplicates: false,
    friends: [],
    areEqual: (a, b) => a === b,
    stopAfter: 10,
  });

  // Remove duplicates from the list of connections
  return [...new Set(connections)];
}

export default listConnections;

Code Breakdown

Dependencies and Import

listConnections Function

Args and Return Value

Logic

  1. Check and Initialize Driver
  2. Get Current URL and Login If Necessary
  3. Get All Connections Until Condition Is Met
  4. Clean and Return Result

Export