Here is the right code for Whatsapp automation using python:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# Set the path to the Chrome driver executable
driver = webdriver.Chrome('/path/to/chromedriver')
# Open WhatsApp Web
driver.get('https://web.whatsapp.com/')
# Wait for the user to scan the QR code
input('Press Enter after scanning the QR code')
# Locate the user or group
user_name = "John Doe"
user_element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, f'//span[@title="{user_name}"]'))
)
user_element.click()
# Find the message input box
msg_box = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.CLASS_NAME, '_1Plpp'))
)
# Compose and send a message
message = "Hello, this is an automated message!"
msg_box.send_keys(message)
send_button = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.CLASS_NAME, '_35EW6'))
)
send_button.click()
# Quit the driver and close the browser
driver.quit()
In this example, we first import the necessary modules from the Selenium library. We then set the path to the Chrome driver executable and create a new instance of the Chrome WebDriver. The script opens WhatsApp Web by navigating to the URL.
After prompting the user to scan the QR code, the script locates the desired user or group by their name using an XPath expression. It then clicks on the user or group to open the chat.
Next, the script finds the message input box and enters the desired message into it. Finally, it locates and clicks the send button to send the message.
At the end of the script, the driver is properly quit, and the browser is closed.
Please note that you need to replace '/path/to/chromedriver'
with the actual path to your Chrome driver executable. Also, make sure you have installed the Selenium library and have the Chrome driver downloaded and available in the specified path.