Automate Your Instagram Activity: A Step-by-Step Guide to Creating a Bot with Selenium JavaScript

ยท

6 min read

Instagram is one of the most popular social media platforms, with over a billion monthly active users. With such a large user base, it's no surprise that many people are interested in automating their Instagram accounts. One way to do this is by using a bot that can perform various actions on your behalf, such as liking posts, following users, or even managing your followers.

In this blog post, we'll be exploring how to create an Instagram bot using Selenium JavaScript. Selenium is a tool that allows you to automate web browsers, making it an ideal choice for building bots. We will be creating a bot that deletes all the requests in the notifications section of an Instagram account.

First: set up a development environment and install the necessary dependencies

  1. Node.js: a JavaScript runtime environment that allows you to run JavaScript code outside of a browser.

  2. Selenium WebDriver: a library that allows you to control web browsers programmatically.

  3. Firefox browser: the browser that we'll be using in this example.

  4. dotenv: a module that allows you to load environment variables from a .env file.

Once you've installed Node.js, run the following commands in your terminal to create a new project:

npm init -y

Next, install the required dependencies by running the following command:

npm install selenium-webdriver firefox dotenv

Now that we have our development environment set up, we can start building our Instagram bot. Here's a step-by-step process to code the bot

  • Here, we start by importing the necessary libraries and dependencies. We're using the dotenv library to load environment variables from a .env file, the selenium-webdriver library to interact with the browser, and the selenium-webdriver/firefox library to use the Firefox browser driver.

  • create your own '.env' file to put your own username and password details

require('dotenv').config();

const { Builder, By, Key, until } = require('selenium-webdriver');
const firefox = require('selenium-webdriver/firefox');
const options = new firefox.Options();

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

We also define a sleep function that we'll use to pause the script for a certain number of milliseconds.

  • We use an asynchronous function to run the script. Inside the function, we create a new instance of the Firefox browser driver using the Builder class from the selenium-web driver. We also log a message to indicate that the browser is being opened.
(async function example() {
  let driver = await new Builder().forBrowser('firefox').build();
  console.log('opening the browser');
  • Next, we use the driver.get a method to navigate to the Instagram website and log a message indicating that the website has been loaded. We also use the sleep function to pause the script for 5 seconds to allow the website to fully load.
try {
    //go to instagram and login - done
    await driver.get('https://www.instagram.com');
    console.log('instagram is loaded');
    await sleep(5000);

    // Wait for the username field to be located, enter the username and password, and submit the form
    await driver.wait(until.elementLocated(By.name('username')), 10000); 
    await driver.findElement(By.name('username')).sendKeys(process.env.INSTAGRAM_USERNAME); 
    await driver.findElement(By.name('password')).sendKeys(process.env.INSTAGRAM_PASSWORD); 
    await sleep(3000);
    await driver.findElement(By.className('_acan _acap _acas _aj1-')).click(); 
    console.log('logged into your acc');
  • Then, we use the driver.wait method to wait for the username field to be located, and use the driver.findElement method to locate the username and password fields on the page. We then use the sendKeys method to input the Instagram username and password, and use the driver.findElement method to locate the login button and click it.

    Finally, we log a message indicating that the user has been logged in.

// Click the notification button 
await driver.wait(until.elementLocated(By.css('[aria-label="Notifications"]')), 10000);
await driver.wait(until.elementIsEnabled(driver.findElement(By.css('[aria-label="Notifications"]'))), 10000);
await driver.findElement(By.css('[aria-label="Notifications"]')).click();
console.log('notification button clicked');

await sleep(5000);
  • This part of the code clicks the notification button on Instagram, which is located in the sidebar of the page and then loads the list of pending friend requests.
let count = 2;
while (true) {
  try {
    let xpath = `/html/body/div[2]/div/div/div[1]/div/div/div/div[1]/div[1]/div[1]/div/div/div[2]/div/div/div/div/div[${count}]/div[3]/div[2]/div`;
    await driver.wait(until.elementLocated(By.xpath(xpath)), 10000);
    let deleteElement = await driver.findElement(By.xpath(xpath));
    await driver.executeScript("arguments[0].scrollIntoView(true);", deleteElement);
    await driver.wait(until.elementIsEnabled(deleteElement), 10000);
    await deleteElement.click();
    console.log(`Deleted request ${count}`);
    await sleep(3000);
    count++;
  } catch (err) {
    console.log("No more requests to delete");
    break;
  }
}

In the final step, we use a loop to iterate over the list to delete all the pending requests. Here's what the code does:

The loop starts at index 2, since the first request is located there and runs an infinite loop until a break statement is encountered.

let xpath = /html/body/div[2]/div/div/div[1]/div/div/div/div[1]/div[1]/div[1]/div/div/div[2]/div/div/div/div/div[${count}]/div[3]/div[2]/div;
  • This line constructs an XPath expression to locate the "Delete" button for the current follow request.
 await driver.wait(until.elementLocated(By.xpath(xpath)), 10000);
    let deleteElement = await driver.findElement(By.xpath(xpath));
    await driver.executeScript("arguments[0].scrollIntoView(true);", deleteElement);
  • These three lines scroll the page down after finding the delete element on the page using Xpath
await driver.wait(until.elementIsEnabled(deleteElement), 10000);
    await deleteElement.click();
    console.log(`Deleted request ${count}`);
    await sleep(3000);
    count++;
} catch (err) {
    console.log("No more requests to delete");
    break;
  }
  • this piece of code clicks on the delete button and console logs the no.of deleted requests and then increments the count.

  • If the loop condition fails then it console logs a message saying there are no more requests to delete.

 } finally {    
    await driver.quit();
  }
})();
  • The finally block contains the driver.quit() method, which closes the browser and releases the resources used by the WebDriver. This ensures that the program exits cleanly, even if an error occurs during execution.

YOU ARE ALL SET!

node bot.js

Just type in this command in the terminal and let the bot do the work for you. Sit back, relax, and watch the magic happen.

Here's the complete code:๐Ÿ’ป

require('dotenv').config();

const { Builder, By, Key, until } = require('selenium-webdriver');
const firefox = require('selenium-webdriver/firefox');
const options = new firefox.Options();

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

(async function example() {
  let driver = await new Builder().forBrowser('firefox').build();
  console.log('opening the browser');

  try {
    //go to instagram and login - done
    await driver.get('https://www.instagram.com');
    console.log('instagram is loaded');
    await sleep(5000);

    // Wait for the username field to be located, enter the username and password, and submit the form
    await driver.wait(until.elementLocated(By.name('username')), 10000); 
    await driver.findElement(By.name('username')).sendKeys(process.env.INSTAGRAM_USERNAME); 
    await driver.findElement(By.name('password')).sendKeys(process.env.INSTAGRAM_PASSWORD); 
    await sleep(3000);
    await driver.findElement(By.className('_acan _acap _acas _aj1-')).click(); // Click the login button
    console.log('logged into your acc');

    // Wait for 5 seconds
    await sleep(5000);

    // Click "Not Now" to dismiss the "Turn on Notifications" prompt
    await driver.wait(until.elementLocated(By.className('_a9-- _a9_1')), 10000);
    await driver.wait(until.elementIsEnabled(driver.findElement(By.className('_a9-- _a9_1'))), 10000);
    await driver.findElement(By.className('_a9-- _a9_1')).click();

    await sleep(3000);

    // Click the notification button 
    await driver.wait(until.elementLocated(By.css('[aria-label="Notifications"]')), 10000);
    await driver.wait(until.elementIsEnabled(driver.findElement(By.css('[aria-label="Notifications"]'))), 10000);
    await driver.findElement(By.css('[aria-label="Notifications"]')).click();
    console.log('notification button clicked');

    await sleep(5000);

    // Click "See All" to view all notifications in the sidebar
    await driver.wait(until.elementLocated(By.css('[aria-label=""]')), 10000);
    await driver.wait(until.elementIsEnabled(driver.findElement(By.css('[aria-label=""]'))), 10000);
    await driver.findElement(By.css('[aria-label=""]')).click();
    console.log('notification sidebar loaded');

    // Delete all pending follow requests
    let count = 2;
    while (true) {
      try {
        let xpath = `/html/body/div[2]/div/div/div[1]/div/div/div/div[1]/div[1]/div[1]/div/div/div[2]/div/div/div/div/div[${count}]/div[3]/div[2]/div`;
        await driver.wait(until.elementLocated(By.xpath(xpath)), 10000);
        let deleteElement = await driver.findElement(By.xpath(xpath));
        await driver.executeScript("arguments[0].scrollIntoView(true);", deleteElement);
        await driver.wait(until.elementIsEnabled(deleteElement), 10000);
        await deleteElement.click();
        console.log(`Deleted request ${count}`);
        await sleep(3000);
        count++;
      } catch (err) {
        console.log("No more requests to delete");
        break;
      }
    }
  } finally {    
    await driver.quit();
  }
})();

In conclusion, we have seen how to build an Instagram bot using Selenium and Node.js. With the code provided, we were able to automatically delete all pending follow requests on Instagram. This code can also be modified to perform other tasks such as accepting follow requests or posting comments. With some creativity, the possibilities are endless. The automation of these tasks can save time and make managing Instagram accounts more efficient. However, it is important to use these tools ethically and within the terms of service of the platform.

ย