Automate WhatsApp Messaging with Python, Selenium, and ChromeDriver

Automate WhatsApp Messaging with Python, Selenium, and ChromeDriver

Total Views - 48
   ||   Total likes - 0
By Jitender   ||    15 February 2025   ||     10 min read

Automating WhatsApp messages can save time and improve efficiency, especially for businesses and individuals managing bulk communications. This comprehensive guide walks you through automating WhatsApp using Python, Selenium, and ChromeDriver. From environment setup to writing and executing automation scripts, you will find detailed steps, best practices, and essential code snippets. Perfect for developers, businesses, and automation enthusiasts looking to leverage technology for effective communication.

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?

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

Tools Required

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

Setting Up Your Environment

  • Install Python: Download Python and install it.
  • Install Selenium: Run pip install selenium in your terminal.
  • 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.

Copy ❐
1import pyperclip
2from selenium.webdriver.chrome.service import Service
3import undetected_chromedriver as webdriver
4from selenium.webdriver.common.by import By
5from selenium.webdriver.chrome.options import Options
6from selenium.webdriver.common.keys import Keys
7from selenium.webdriver.support.ui import WebDriverWait
8from selenium.webdriver.support import expected_conditions as EC
9from selenium.common.exceptions import NoSuchElementException, TimeoutException
10import re
11import time
12
13
14driver_path = "C://Program Files//Google//Chrome//Application//chrome.exe" # Update this path to match your driver location
15profile_path = "C://Users//perso//AppData//Local//Google//Chrome//User Data" # Update this path
16profile_name = "Profile 8"
17
18# Set Chrome options
19chrome_options = webdriver.ChromeOptions()
20chrome_options.arguments.append(f"--user-data-dir={profile_path}")
21chrome_options.arguments.append(f"--profile-directory={profile_name}")
22chrome_options.add_argument("--start-fullscreen")
23
24service = Service(driver_path)
25chrome_options.use_chromium = True
26driver = webdriver.Chrome(service=service, options=chrome_options)
27
28driver.get("https://web.whatsapp.com/")
29WebDriverWait(driver, 60).until(EC.presence_of_element_located((By.XPATH, "//span[@data-icon='new-chat-outline']")))
30numbers = [
31 {
32 "name": "Hello",
33 "number": "+625462482736"
34 }
35]
36for user in numbers:
37 try:
38 chat_button_icon = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//span[@data-icon='new-chat-outline']")))
39 chat_button_icon.click()
40 search_box = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//div[@aria-label='Search name or number']")))
41 search_box.clear()
42 search_box.send_keys(user["number"])
43 time.sleep(30)
44 try:
45 invalid_warning = driver.find_element(By.XPATH, "//*[contains(text(), 'No results found for')]")
46 invalid = driver.find_element(By.XPATH, "//div[@aria-label='Back']//span[@aria-hidden='true']")
47 invalid.click()
48 continue
49 except NoSuchElementException:
50 pass
51 search_box.send_keys(Keys.ENTER)
52 message = f"""🚀 Your Friend or Relative ( Jennifer Wrieden ) Just Joined Lit Star! Don't Miss Out!
53
54Hey {user['name']},
55
56Your friend or Relative @magentatv202488 just joined Lit Star! 🎉 Stay connected, follow them, and see what theyre up to!
57
58🔥 Install now & join the fun!
59👉 https://play.google.com/store/apps/details?id=com.litstar
60
61After installing, tap below to view their profile:
62📸 https://www.litstar.iplust.in/app/user/462
63
64Engage, follow, and enjoy! 🚀✨
65
66Lit StarWhere Connections Shine! 🌟"""
67 pyperclip.copy(message)
68 time.sleep(1)
69 message_box = driver.switch_to.active_element
70 message_box.send_keys(Keys.CONTROL, 'v')
71 time.sleep(1)
72 message_box.send_keys(Keys.ENTER)
73 time.sleep(2)
74
75 except (NoSuchElementException, TimeoutException) as e:
76 print(f"Error sending message to {user['name']}: {e}")
77
78driver.quit()

Understanding the Code

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

Best Practices

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

Benefits of WhatsApp Automation

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

Challenges and Solutions

  • 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 Blog ...

Top Results
Tags
Ads
banner