Home > Blockchain >  Cannot send message in a loop using whatsapp automation (selenium)
Cannot send message in a loop using whatsapp automation (selenium)

Time:12-01

I am using this code to automate WhatsApp message sending, But the loop applied to send a message number of times is not working properly. It just sends a message once and stops.

Kindly help!

Following is the code:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time



options=webdriver.ChromeOptions()
options.add_argument("user-data-dir=C:/Users/Sameer/AppData/Local/Google/Chrome/User Data/Person 1")
# options.add_argument('--profile-directory=Default')
driver=webdriver.Chrome(executable_path='chromedriver.exe',options=options)
driver.get("https://web.whatsapp.com/")
wait=WebDriverWait(driver,100)

target='"My 2"'
message="Hello"
# number_of_times=10 #No. of times to send a message

contact_path='//span[contains(@title,'  target  ')]'
contact=wait.until(EC.presence_of_element_located((By.XPATH,contact_path)))
contact.click()
message_box_path='//*[@id="main"]/footer/div[1]/div/span[2]/div/div[2]/div[1]/div/div[1]/p'
# '//*[@id="main"]/footer/div[1]/div/span[2]/div/div[2]/div[1]/div/div[1]'
message_box=wait.until(EC.presence_of_element_located((By.XPATH,message_box_path)))

for x in range(5):
    message_box.click()
    message_box.clear()
    message_box.send_keys(message)
    message_box.send_keys(Keys.ENTER)
    # time.sleep(0.2)

    # print(x)
    # message_box.send_keys(message   Keys.ENTER)
    # time.sleep(0.2)

CodePudding user response:

Try locating the message_box inside the loop.
Also, you have to improve your locators.
And it should be element_to_be_clickable expected condition there, not just presence_of_element_located.
So, please try this code:

message_box_path='//footer//p'
for x in range(5):
    message_box=wait.until(EC.element_to_be_clickable((By.XPATH,message_box_path)))
    message_box.click()
    message_box.clear()
    message_box.send_keys(message   Keys.ENTER)
    time.sleep(0.2)
  • Related