In this article, we will be using python and selenium to automate some messages on WhatsApp.
I hope the reader is well aware of python beforehand.
The first and the foremost step is to install python3 which you can download from https://www.python.org/ and follow up the install instruction. After the installation will be complete, install selenium for the automation of all the tasks we want to perform.
python3 -m pip install Selenium
Selenium Hello World:
After installing selenium, to check whether it is installed correctly or not, run the python code mentioned below and check if there are any errors.
from selenium import webdriver import time driver = webdriver.Chrome() driver.get("http://google.com") time.sleep(2) driver.quit()
Save this code in a python file and name it according to your preference. If the program runs correctly without showing any errors, then the Google Chrome window will be opened automatically.
Automate Whatsapp:
Import the modules selenium and time like below.
from selenium import webdriver import time
After the importing of the modules, the below code will open the WhatsApp web interface which will automatically ask you to scan the QR code and will be logged into your account.
driver = webdriver.Chrome() driver.get("https://web.whatsapp.com") print("Scan QR Code, And then Enter") time.sleep(5)
The next step is entering the username to whom you want to send the message. In my case, I made a group named “WhatsApp bot” and then located an XPath using the inspect method and put it in.
As soon as the WhatsApp bot will be opened, it will automatically locate the WhatsApp bot and will enter that window.
user_name = 'Whatsapp Bot' user = driver.find_element_by_xpath('//span[@title="{}"]'.format(user_name)) user.click()
After this, the message box will be opened and now you have to inspect the message box and enter the message you want to send. Later, you have to inspect the send button and click on it using the click() method.
message_box = driver.find_element_by_xpath('//div[@class="_2A8P4"]') message_box.send_keys('Hey, I am your whatsapp bot') message_box = driver.find_element_by_xpath('//button[@class="_1E0Oz"]') message_box.click()
As soon as you execute this code, the message will be sent and your work is done.
I am attaching the whole code for your reference.
from selenium import webdriver import time driver = webdriver.Chrome(executable_path=””) time.sleep(5) user_name = 'Whatsapp Bot' user = driver.find_element_by_xpath('//span[@title="{}"]'.format(user_name)) user.click() message_box = driver.find_element_by_xpath('//div[@class="_2A8P4"]') message_box.send_keys('Hey, I am your whatsapp bot') message_box = driver.find_element_by_xpath('//button[@class="_1E0Oz"]') message_box.click() driver.quit()
At the end we put driver.quit() method to end the execution of the task.
You did a great job making this bot!!