Whatsapp using Python!
Developer’s can automate the browser’s activity with a very smart package in python called Selenium. We can make use of whatsapp-web through the browser by using this.
Requirements
We require three basic things to get things fulfill: Selenium.
Install selenium using pip by running the below command on your terminal −
$pip install selenium
- Chrome/firefox or any other webdriver.
As I using chrome webdriver, below is a link to download chrome webdriver as per your os.
- https://chromedriver.storage.googleapis.com/index.html?path=2.46/
- Whatsapp account.
Create Whatsapp account.
Below code is an example to send whatsapp message using python to specific contacts.
Example
from selenium importwebdriver from selenium.webdriver.support.uiimportWebDriverWait from selenium.webdriver.supportimportexpected_conditions as EC from selenium.webdriver.common.keysimportKeys from selenium.webdriver.common.byimportBy 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') driver.get("https://web.whatsapp.com/") #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") group_title.click() message =driver.find_elements_by_xpath('//*[@id="main"]/footer/div[1]/div[2]/div/div[2]')[0] message.send_keys(string) sendbutton=driver.find_elements_by_xpath('//*[@id="main"]/footer/div[1]/div[3]/button')[0] sendbutton.click() driver.close()
Run the above scripts on command prompt by passing message as argument to the whatsapp contact−
>python whatsppPython.py "Hello" DevTools listening on ws://127.0.0.1:12954/devtools/browser/a5bb04bd-66a3-4002-999f-6a0824f591da <selenium.webdriver.remote.webelement.WebElement(session="83e7034b9a6f6b49e9e422e655f270d3", element="0.30994636046479007-1")> after wait …. …..
As shown below the chrome browser will open with screen something like −
On your mobile device, Choose whatsapp web from the top bar in whatsapp. On the screen, scan the QR code that appears.
There we can see the message is send to a specific contact (“My Bsnl”) in our case.