In this article, we will learn how we can send a direct message to users on Instagram without any manual action. We will be using the selenium module to do this task.
Requirements:
- Chrome Driver for Chrome Browser (https://chromedriver.chromium.org/) or Gecko Driver for Firefox(https://github.com/mozilla/geckodriver/releases)
- Selenium Package. To install this type the below command in the terminal.
pip install selenium
Note: For more information, refer How to install Selenium in Python
Approach:
Step 1: Importing modules and entering the login information along with the username of the user whom you want to send a message.
Python3
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import selenium.common.exceptions
import time
import random
username = input ( 'Enter your Username ' )
password = input ( 'Enter your Password ' )
|
Step 2: Function to initialize Firefox or chrome session. You might need to add the path to the web driver. Chrome function, it depends on your installation.
Python3
def path():
global chrome
chrome = webdriver.Chrome()
|
Step 3: Function to enter the URL of the page
Python3
def url_name(url):
chrome.get(url)
time.sleep( 4 )
|
Step 4: Function to login to Instagram
Python3
def login(username, your_password):
log_but = chrome.find_element_by_class_name( "L3NKy" )
time.sleep( 2 )
log_but.click()
time.sleep( 4 )
usern = chrome.find_element_by_name( "username" )
usern.send_keys(username)
passw = chrome.find_element_by_name( "password" )
passw.send_keys(your_password)
passw.send_keys(Keys.RETURN)
time.sleep( 5.5 )
notk = chrome.find_element_by_class_name( "yWX7d" )
notk.click()
time.sleep( 3 )
|
Step 5: Find the message Button on the User profile page and then send random messages to the user
Python3
def send_message():
message = chrome.find_element_by_class_name( '_862NM ' )
message.click()
time.sleep( 2 )
chrome.find_element_by_class_name( 'HoLwm ' ).click()
time.sleep( 1 )
l = [ 'hello' , 'Hi' , 'How are You' , 'Hey' , 'Bro whats up' ]
for x in range ( 10 ):
mbox = chrome.find_element_by_tag_name( 'textarea' )
mbox.send_keys(random.choice(l))
mbox.send_keys(Keys.RETURN)
time.sleep( 1.2 )
|
Step 6: Calling Functions
Python3
path()
time.sleep( 1 )
url_name(url)
login(username, password)
send_message()
chrome.close()
|
That’s it! This script will automatically send messages to your loved one. You can do a lot by modifying this script like scheduling automatic messages, sending messages to bulk users and many more.
Output: