Automate WhatsApp Messaging with Python, Selenium, and ChromeDriver

Share this blog

Introduction

In today's fast-paced world, automation plays a crucial role in enhancing productivity. WhatsApp, being one of the most popular messaging platforms, can benefit significantly from automation. Whether you are a business managing bulk communications or an individual looking to automate repetitive tasks, this guide will help you automate WhatsApp messaging using Python, Selenium, and ChromeDriver.


Why Automate WhatsApp?

  1. Save Time: Automate repetitive messaging tasks.
  2. Improve Efficiency: Handle bulk messages without manual intervention.
  3. Enhance Communication: Ensure timely and consistent communication.
  4. Business Use: Automate customer service, marketing campaigns, and more.


Tools Required

  1. Python: A versatile programming language.
  2. Selenium: A web automation tool.
  3. ChromeDriver: A driver for Google Chrome that allows Selenium to interact with the browser.


Setting Up Your Environment

  1. Install Python: Download Python and install it.
  2. Install Selenium: Run pip install selenium in your terminal.
  3. Download ChromeDriver: Get ChromeDriver and place it in your system's PATH.


Writing the Automation Code

Below is the complete code to automate WhatsApp messaging. You can also download the code here.


import pyperclip
from selenium.webdriver.chrome.service import Service
import undetected_chromedriver as webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException, TimeoutException
import re
import time


driver_path = "C://Program Files//Google//Chrome//Application//chrome.exe" # Update this path to match your driver location
profile_path = "C://Users//perso//AppData//Local//Google//Chrome//User Data" # Update this path
profile_name = "Profile 8"

# Set Chrome options
chrome_options = webdriver.ChromeOptions()
chrome_options.arguments.append(f"--user-data-dir={profile_path}")
chrome_options.arguments.append(f"--profile-directory={profile_name}")
chrome_options.add_argument("--start-fullscreen")

service = Service(driver_path)
chrome_options.use_chromium = True
driver = webdriver.Chrome(service=service, options=chrome_options)

driver.get("https://web.whatsapp.com/")
WebDriverWait(driver, 60).until(EC.presence_of_element_located((By.XPATH, "//span[@data-icon='new-chat-outline']")))
numbers = [
{
"name": "Hello",
"number": "+625462482736"
}
]
for user in numbers:
try:
chat_button_icon = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//span[@data-icon='new-chat-outline']")))
chat_button_icon.click()
search_box = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//div[@aria-label='Search name or number']")))
search_box.clear()
search_box.send_keys(user["number"])
time.sleep(30)
try:
invalid_warning = driver.find_element(By.XPATH, "//*[contains(text(), 'No results found for')]")
invalid = driver.find_element(By.XPATH, "//div[@aria-label='Back']//span[@aria-hidden='true']")
invalid.click()
continue
except NoSuchElementException:
pass
search_box.send_keys(Keys.ENTER)
message = f"""🚀 Your Friend or Relative ( Jennifer Wrieden ) Just Joined Lit Star! Don't Miss Out!

Hey {user['name']},

Your friend or Relative @magentatv202488 just joined Lit Star! 🎉 Stay connected, follow them, and see what they’re up to!

🔥 Install now & join the fun!
👉 https://play.google.com/store/apps/details?id=com.litstar

After installing, tap below to view their profile:
📸 https://www.litstar.iplust.in/app/user/462

Engage, follow, and enjoy! 🚀✨

Lit Star – Where Connections Shine! 🌟"""
pyperclip.copy(message)
time.sleep(1)
message_box = driver.switch_to.active_element
message_box.send_keys(Keys.CONTROL, 'v')
time.sleep(1)
message_box.send_keys(Keys.ENTER)
time.sleep(2)

except (NoSuchElementException, TimeoutException) as e:
print(f"Error sending message to {user['name']}: {e}")

driver.quit()


Understanding the Code

  1. Selenium Setup: Initiates ChromeDriver and opens WhatsApp Web.
  2. Loop Through Contacts: Automates sending messages to each contact in the list.


Best Practices

  1. Avoid Spamming: Automate responsibly.
  2. Add Delays: Include time gaps to prevent account restrictions.
  3. Secure Your Data: Keep contacts and messages secure.


Benefits of WhatsApp Automation

  1. Bulk Messaging: Send messages to multiple contacts simultaneously.
  2. Time-Saving: Reduces manual effort.
  3. Consistency: Ensures uniform messaging.


Challenges and Solutions

  1. WhatsApp Web Limitations: Automation should respect platform policies.


Conclusion

Automating WhatsApp messaging using Python, Selenium, and ChromeDriver can transform your communication strategy. Whether you're a developer, business owner, or tech enthusiast, this guide provides all the tools and knowledge you need to get started.


Happy Automating! 🚀


Comments Of This Post ...