Automate Your Instagram Close Friends List with Playwright

Instagram

Automate Your Instagram Close Friends List with Playwright

In today's fast-paced digital world, automation can save you valuable time—even on social media. One common task that can be automated is adding a list of people to your Instagram Close Friends list. In this article, we'll walk you through a script built with Playwright that does just that.

Disclaimer: This script is for educational purposes only. Automating interactions on Instagram may violate their terms of service, so use it responsibly and at your own risk.

What Does the Script Do?

The script is written in Node.js using the Playwright library to automate browser actions. Here’s a quick rundown of its functionality:

  1. Launch the Browser: The script starts by launching a Chromium browser instance in non-headless mode, allowing you to see the browser actions in real time.
  2. Manual Login: It directs you to Instagram's login page and waits for you to log in manually. Once logged in, navigate to your Close Friends page.
  3. Search and Add Users: The script then iterates over an array of usernames, searches for each user using Instagram's search functionality, and clicks on the appropriate element (the second icon button) to add them to your Close Friends list.

This process automates what would otherwise be a repetitive and time-consuming task, making it a handy tool for those who manage large Close Friends lists.

The Complete Script

Below is the full script with inline comments to help you understand each step:

const { chromium } = require("@playwright/test");

(async () => {
  // Launch the browser in non-headless mode so you can see the automation in action.
  const browser = await chromium.launch({ headless: false });
  const context = await browser.newContext();
  const page = await context.newPage();

  // Navigate to Instagram's homepage.
  await page.goto("https://www.instagram.com/", { waitUntil: "networkidle" });
  console.log(
    "Please log in manually. After that, navigate to your Close Friends page."
  );

  // Define the list of usernames to add to your Close Friends list.
  const usernameToSearch = [
    "selly",
    "beachplease",
    "playboicarti",
    "theweeknd",
  ];

  // Allow time for manual login and navigation.
  await page.waitForTimeout(30000);

  // Start processing the list of usernames.
  await searchCloseFriendUser(page, usernameToSearch);
})();

// Function to search for each username and interact with the Close Friends elements.
async function searchCloseFriendUser(page, users) {
  const searchInputSelector =
    'input[data-bloks-name="bk.components.TextInput"]';

  for (const username of users) {
    try {
      // 1. Wait for the search input to appear.
      await page.waitForSelector(searchInputSelector, { timeout: 10000 });

      // 2. Clear the input field and fill in the username.
      await page.fill(searchInputSelector, ""); // Clear the input if needed
      await page.fill(searchInputSelector, username);

      // 3. Trigger the search by pressing Enter.
      await page.keyboard.press("Enter");

      // 4. Wait for the search results to load.
      await page.waitForTimeout(2000); // Wait 2 seconds

      // 5. Define the selector for the icon element used to add close friends.
      const iconSelector = 'div[data-bloks-name="ig.components.Icon"]';

      // Wait for the icon elements to load.
      await page.waitForSelector(iconSelector, { timeout: 10000 });

      // 6. Get all matching icon elements.
      const iconElements = await page.$$(iconSelector);

      // Ensure there are at least two elements, then click the second one.
      if (iconElements.length >= 2) {
        await iconElements[1].click(); // Click the second element (index 1)
        console.log(
          `Searched for "${username}" and clicked the second "ig.components.Icon" result.`
        );
      } else {
        console.log(
          `Not enough "ig.components.Icon" elements found for "${username}".`
        );
      }

      // 7. Clear the search input for the next username.
      await page.fill(searchInputSelector, ""); // Clear the input
    } catch (error) {
      console.log(`Error processing "${username}": ${error.message}`);
    }
  }
}

How It Works

Manual Intervention

The script intentionally pauses for 30 seconds after reaching the Instagram homepage to allow for manual login. This is crucial since automating the login process can trigger security checks on Instagram.

Searching for Users

The searchCloseFriendUser function takes an array of usernames, iterates over them, and performs a search using the designated input field. After entering each username, it simulates an "Enter" key press to load the results.

Interacting with Search Results

Once the search results appear, the script waits for the icon elements (which are associated with adding users to the Close Friends list) to load. It then clicks on the second icon (assuming this is the correct one for the action) for each user.

Error Handling

If any part of the process fails (e.g., if the expected elements are not found), the script logs an error message and continues with the next username.

Final Thoughts

Automation scripts like this one can dramatically reduce the manual effort required for managing social media interactions. By leveraging Playwright, you can customize and extend this script to suit other repetitive tasks on Instagram or similar platforms.

Remember, while automation can boost efficiency, it's important to respect platform guidelines and avoid actions that may be considered spammy or against the terms of service. Use this script as a learning tool and modify it according to your needs.

Happy coding and automating!

Reflect Ui is a rapid content delivery platform that helps you deliver content to your users in a fast and efficient way.
Designed and Developed by Reflect UI