Skip to main content

Code python/selenium to send bulk whatsapp messages - continiously unable to locate element for text box

Looked at many options and other codes. Everything in the code below runs smoothly, until the whatsapp input box is called up with:

*input_box = driver.find_element_by_xpath('//*[@id="main"]/footer/div[1]/div[2]/div/div[2]')*

I have also adjusted it to:

*input_box = driver.find_element(By.XPATH, '//*@id="main"]/footer/div[1]/div[2]/div/div[2]')*

without any success. I get the following error:


Klaas Malan *(my contact)*
As jy hierdie teks kry, dan werk die program wat ek vir Heiko skrywe. *(Message in Afrikaans)*
https://web.whatsapp.com/send?phone=Klaas Malan&text=As+jy+hierdie+teks+kry%2C+dan+werk+die+program+wat+ek+vir+Heiko+skrywe.&source=&data=
Sending message to Klaas Malan
**Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="main"]/footer/div[1]/div[2]/div/div[2]"}**
  (Session info: chrome=101.0.4951.54)
Failed to send message

Below my full 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.keys import Keys
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.action_chains import ActionChains

import datetime
import time
import openpyxl as excel
import urllib.parse

# function to read contacts from a text file
def readContacts(fileName):
    lst = []
    file = excel.load_workbook(fileName)
    sheet = file.active
    firstCol = sheet['A']
    secondCol = sheet['B']
    driver  = webdriver.Chrome()
    driver.get('https://web.whatsapp.com')
    time.sleep(60)

    for cell in range(len(firstCol)):
        contact = str(firstCol[cell].value)
        message = str(secondCol[cell].value)
        print(contact)
        print(message)
        link = "https://web.whatsapp.com/send phone="+contact+"&text="+urllib.parse.quote_plus(message)+"&source=&data="
        print(link)  
        driver.get(link)
        time.sleep(4)
        print("Sending message to", contact)

        try:
            time.sleep(7)
            input_box = driver.find_element_by_xpath('//*[@id="main"]/footer/div[1]/div[2]/div/div[2]')
            for ch in message:
                if ch == "\n":
                    ActionChains(driver).key_down(Keys.SHIFT).key_down(Keys.ENTER).key_up(Keys.ENTER).key_up(Keys.SHIFT).key_up(Keys.BACKSPACE).perform()
                else:
                    input_box.send_keys(ch)
            input_box.send_keys(Keys.ENTER)
            print("Message sent successfuly")
        except NoSuchElementException as exc:
            print(exc) # and/or other actions to recover
            print("Failed to send message")

targets = readContacts("./contacts-message.xlsx")

Is there anyone with a suggestion or who are willing to share their code? Best wishes, folks. I am very new to Python and a farmer in Namibia, and I aim to send to separate message for each of my cattle buyers thanking them. Emil Jung



source https://stackoverflow.com/questions/72164320/code-python-selenium-to-send-bulk-whatsapp-messages-continiously-unable-to-loc

Comments

Popular posts from this blog

Where and how is this Laravel kernel constructor called? [closed]

Where and how is this Laravel kernel constructor called? public fucntion __construct(Application $app, $Router $roouter) { } I have read the documentation and some online tutorial but I can find any clear explanation. I am learning Laravel and I am wondering where does this kernel constructor receives its arguments from. "POSTMOTERM" CLARIFICATION: Here is more clarity.I have checked the boostrap/app.php and it is only used for boostrapping the interfaces into the container class. What is not clear to me is where and how the Kernel class is instatiated and the arguments passed to the object calling the constructor.Something similar to; obj = new kernel(arg1,arg2) or, is the framework using some magic functions somewhere? Special gratitude to those who burn their eyeballs and brain cells on this trivia before it goes into a full blown menopause alias "MARKED AS DUPLICATE". To some of the itchy-finger keyboard warriors, a.k.a The mods,because I believe in th...

Why is my reports service not connecting?

I am trying to pull some data from a Postgres database using Node.js and node-postures but I can't figure out why my service isn't connecting. my routes/index.js file: const express = require('express'); const router = express.Router(); const ordersCountController = require('../controllers/ordersCountController'); const ordersController = require('../controllers/ordersController'); const weeklyReportsController = require('../controllers/weeklyReportsController'); router.get('/orders_count', ordersCountController); router.get('/orders', ordersController); router.get('/weekly_reports', weeklyReportsController); module.exports = router; My controllers/weeklyReportsController.js file: const weeklyReportsService = require('../services/weeklyReportsService'); const weeklyReportsController = async (req, res) => { try { const data = await weeklyReportsService; res.json({data}) console...

Confusion between commands.Bot and discord.Client | Which one should I use?

Whenever you look at YouTube tutorials or code from this website there is a real variation. Some developers use client = discord.Client(intents=intents) while the others use bot = commands.Bot(command_prefix="something", intents=intents) . Now I know slightly about the difference but I get errors from different places from my code when I use either of them and its confusing. Especially since there has a few changes over the years in discord.py it is hard to find the real difference. I tried sticking to discord.Client then I found that there are more features in commands.Bot . Then I found errors when using commands.Bot . An example of this is: When I try to use commands.Bot client = commands.Bot(command_prefix=">",intents=intents) async def load(): for filename in os.listdir("./Cogs"): if filename.endswith(".py"): client.load_extension(f"Cogs.{filename[:-3]}") The above doesnt giveany response from my Cogs ...