Whatsapp using Python?

PythonServer Side ProgrammingProgramming

In this section we are going to create a Whatsapp chatbots, but unlike few other chatbots for twitter or facebook, whatsapp chatbots don’t run on the platform directly because of whatsapp’s policies.

But there is a way to get is done, using selenium, a very smart package in python with which developer’s can automate the browser’s activity. With this we can make use of whatsapp-web through the browser.


We need three basic things to get things done: Selenium.

We can install selenium very easily using pip, just run below command on your terminal −

$pip install selenium

Below is a simple program to send whatsapp message using python to specific contacts.


from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import time
import sys
# Replace below path with the absolute path of the \
#chromedriver in your computer
driver = webdriver.Chrome(r'c:\users\rajesh\Desktop\chromedriver')

# time.sleep()
wait = WebDriverWait(driver, 600)
# Replace 'My Bsnl' with the name of your friend or group name
target = '"My Bsnl"'

# Replace the below string with your own message
string = sys.argv[1]

x_arg = '//span[contains(@title,' + target + ')]'
group_title = wait.until(EC.presence_of_element_located((
By.XPATH, x_arg)))
print (group_title)
print ("Wait for few seconds")
message = driver.find_elements_by_xpath('//*[@id="main"]/footer/div[1]/div[2]/div/div[2]')[0]

sendbutton = driver.find_elements_by_xpath('//*[@id="main"]/footer/div[1]/div[3]/button')[0]

Let’s run the above scripts on command prompt, passing message as argument to the whatsapp contact−

>python whatsppPython.py "Hello"

DevTools listening on ws://
<selenium.webdriver.remote.webelement.WebElement (session="83e7034b9a6f6b49e9e422e655f270d3", element="0.30994636046479007-1")>
after wait

chrome browser will open, with a screen something like −

On your mobile device, Choose whatsapp web from the top bar in whatsapp. Scan the QR code that appears on the screen.

There we can see the message is send to a specific contact (“My Bsnl”) in our case.

Updated on 30-Jul-2019 22:30:26