Python code to Automate Instagram Login

12607

Table of Contents

Python code to login to Instagram.

To implement this code we will need to import webdriver from the Selenium library, for Python. We will set-up a Chrome driver using Selenium. We need to access the login URL page for Instagram. After that, we need to access XPATH for Instagram such as: username, password form field, and a login button. Finally, we will send a post request by clicking the login button. It is one of the simplest ways to login without using API. Instead of using the requests library, we chose to use Selenium because it makes a job lot easier, as we do not need to set additional parameters.

Python code implementation to login to Instagram using Selenium.

 

Code:

 

from selenium import webdriver
from time import sleep
driver = webdriver.Chrome(executable_path=r'C:\driver\chromedriver.exe')
driver.get('https://www.instagram.com/')
driver.maximize_window()
driver.find_element_by_xpath('/html/body/div[1]/section/main/article/div[2]/div[1]/div/form/div[2]/div/label/input').send_keys('username')
sleep(5)
driver.find_element_by_xpath('/html/body/div[1]/section/main/article/div[2]/div[1]/div/form/div[3]/div/label/input').send_keys('password')
sleep(5)
driver.find_element_by_xpath('/html/body/div[1]/section/main/article/div[2]/div[1]/div/form/div[4]/button/div').click()
sleep(5)
driver.find_element_by_xpath('/html/body/div[4]/div/div/div[3]/button[2]').click()
sleep(5)

 

Steps required to login to Instagram Page using Python

  • Setting up Chrome driver using Selenium
  • Carefully set the Fullpath name, where the chromedriver.exe file is placed.
  • The login page URL (such as https://instagram.com) – GET Request operation
  •  XPATH for username – Send_Keys (it can also be CSS selector, class name or tag instead of XPATH): /html/body/div[1]/section/main/article/div[2]/div[1]/div/form/div[2]/div/label/input
  • XPATH for the password – Send_Keys operation : /html/body/div[1]/section/main/article/div[2]/div[1]/div/form/div[3]/div/label/input
  •  XPATH for the login button. – click() : /html/body/div[1]/section/main/article/div[2]/div[1]/div/form/div[4]/button/div
  • Then sending a post request by clicking login button.