facebook webdriver | facebook login | add friend | Search

The listFriends function is an asynchronous module that lists Facebook friends using Selenium WebDriver, either by logging in and using an existing driver or creating a new one. It extracts friend links from the Facebook suggestions page, filters out duplicates, and returns the result, while handling errors by quitting the Selenium WebDriver session and re-throwing the error.

Run example

npm run import -- "list friends"

list friends


//const fs = require('fs')
const getClient = importer.import("selenium client")
const getAllUntil = importer.import("all elements until")
const loginFacebook = importer.import("facebook login")
//const {FACEBOOK_PATH} = require('./config.js')

async function listFriends(driver) {
  if (!driver) {
    driver = await getClient()
    await loginFacebook(driver)
  }

  try {
    let url = await driver.getCurrentUrl()
    let alreadyThere = url.indexOf('facebook') && url.indexOf('suggestions') > -1
    if (!alreadyThere) {
      await driver.get('https://www.facebook.com/friends/suggestions')
      await new Promise(resolve => setTimeout(resolve, 4000))
    }

    let result = await getAllUntil(driver,
      '//div[@aria-label="Suggestions"]/div/div/following-sibling::div[contains(.//text(), "People you may know")]',
      '//div[@aria-label="Suggestions"]//a[@role="link"]/@href',
      (a, b) => a === b,
      (i) => i < 10,
    )

    return result.filter((l, i, arr) => arr.indexOf(l) === i)
  } catch (e) {
    driver.quit() // avoid leaving sessions hanging around

    throw e
  }
}

module.exports = listFriends

What the code could have been:

import { importers } from './importers.js';
import { FacebookLogin } from './facebook-login.js';
import { SeleniumClient } from './selenium-client.js';

/**
 * List friends on Facebook
 * @param {object} driver - Selenium WebDriver instance
 * @returns {Promise} List of friend URLs
 */
async function listFriends(driver = null) {
  // Ensure driver instance
  if (!driver) {
    driver = await SeleniumClient.getInstance();
    await new FacebookLogin(driver).login();
  }

  try {
    // Get current URL and check if already on friends page
    const url = await driver.getCurrentUrl();
    const alreadyOnFriendsPage = url.indexOf('facebook')!== -1 && url.indexOf('suggestions')!== -1;

    if (!alreadyOnFriendsPage) {
      // Navigate to friends page if not already there
      await driver.get('https://www.facebook.com/friends/suggestions');
      await new Promise(resolve => setTimeout(resolve, 4000));
    }

    // Extract friend URLs from page
    const friendUrls = await getAllElementsUntil(driver, {
      selector: '//div[@aria-label="Suggestions"]/div/div/following-sibling::div[contains(.//text(), "People you may know")]',
      extract: '//div[@aria-label="Suggestions"]//a[@role="link"]/@href',
      compare: (a, b) => a === b,
      limit: 10, // TODO: Refactor to use a more robust limit mechanism
    });

    // Return unique friend URLs
    return [...new Set(friendUrls)];
  } catch (error) {
    // Quit driver instance to avoid leaving sessions hanging
    await driver.quit();

    // Re-throw the error
    throw error;
  }
}

// Export function
export default listFriends;

Function Overview

The listFriends function is an asynchronous module that lists friends on Facebook using Selenium WebDriver.

Parameters

Functionality

  1. If no driver is provided, it creates a new instance using getClient() and logs in to Facebook using loginFacebook().
  2. Checks if the current URL is the Facebook suggestions page. If not, navigates to the page after a 4-second delay.
  3. Uses getAllUntil() to extract friend links from the page. The function waits for the presence of a specific label, searches for a specific pattern in the page, and extracts the href attribute of links.
  4. Filters out duplicate friend links and returns the result.

Error Handling

If an error occurs, the function quits the Selenium WebDriver session and re-throws the error.

Export

The listFriends function is exported as a module.

Imported Functions

Imported Modules