0

I am trying to send whatsapp message to contacts using Python but getting an error: InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression //span[@title = "Me Postpaid"]"} (Session info: chrome=73.0.3683.103) (Driver info: chromedriver=73.0.3683.68 (47787ec04b6e38e22703e856e101e840b65afe72),platform=Windows NT 6.1.7601 SP1 x86_64)

I have used selenium for this and the code is mentioned below:

from selenium import webdriver

driver = webdriver.Chrome('C:/Users/....../chromedriver_win32/chromedriver.exe') 
driver.get('https://web.whatsapp.com/')

name = input('Enter the name of person or group you want to message: ')
msg = input('Enter your Message: ')
count = int(input('Enter how many times you want to send this message: '))


input('Enter any key after scanning QR code')

user = driver.find_element_by_xpath('//span[@title = "        {}"]'.format(name)).click()
#user.click()

msg_box = driver.find_element_by_class_name('_1Plpp')

for i in range(count):

    msg_box.send_keys(msg)
    button = driver.find_element_by_class_name('_35EW6')
    button.click()

enter image description here

How can I make this work ???

Vivi
  • 155
  • 14
  • There might be some characters from the console. What happen if you use hard coded path? `'//span[@title = "Me Postpaid"]'` – Guy Apr 30 '19 at 11:45

2 Answers2

0

click() doesn't returns anything. So you need to remove the assignment and format the line of code properly replacing:

driver.find_element_by_xpath('//span[@title = "{}"]'.format(name)).click()

with:

driver.find_element_by_xpath('//span[@title= "{}"]'.format(name)).click()
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • 1
    Although it's true, it doesn't answer the main problem `InvalidSelectorException`. – Guy Apr 30 '19 at 11:46
  • actually I used correct formatting in code, it was in here while pasting got changed. But using above statement without assigning to `user` worked. So used below statement and it worked now `driver.find_element_by_xpath('//span[@title= "{}"]'.format(name)).click()` Thanks for helping me out!! – Vivi Apr 30 '19 at 11:49
  • @Guy _... it doesn't answer the main problem..._, How differently should we address `InvalidSelectorException` in that particular line ... any suggestions? – undetected Selenium Apr 30 '19 at 11:54
  • @DebanjanB You can see my comment on the question for a possible cause, but blank spaces in the selector are valid, even if this doesn't match anything. – Guy Apr 30 '19 at 11:59
  • @Guy If you still believe **blank spaces in the selector are valid** you may like to explore the difference between **lexical** and **semantical** [here](https://www.oposinet.com/temario-primaria-ingles/temario-2-educacion-primaria-ingles/topic-11-lexical-and-semantic-fields-in-english-lexicon-need-for-socialization-information-and-expression-of-attitudes-typology-linked-to-teaching-and-learning-vocabulary-in-the-foreign-la/) – undetected Selenium Apr 30 '19 at 12:03
  • @Guy I am afraid, if you haven't got the difference by now you may like to ask a question if _...blank spaces in the selector are valid..._. Contributors will be happy to help you out. – undetected Selenium Apr 30 '19 at 12:11
  • 1
    @DebanjanB No need, they are. It might not match anything, but it's still valid. – Guy Apr 30 '19 at 12:26
  • @Guy **No**, it isn't. There is a lot of difference between `lexical` check and `semantical` check which would be too big to answer within a comment for you convenience. – undetected Selenium Apr 30 '19 at 12:30
0

Might be the simple way to send whatsapp message with speak function or automate whatsapp message using python without using selenium

First of all

pip install pywhatkit #it is an module for whatsapp
pip install speechRecognition #it is the module which recognizes what the user speaks

After installing this pip modules import them

import speech_recognition as sr 
import pywhatkit

The main syntax for sending whatsapp message is

pywhatkit.sendwhatmsg(phone_no, msg, time_h, time_m, 15)

Secondly define a function like this:

engine = pyttsx3.init('sapi5') # to take voice & search in google
voices = engine.getProperty('voices')
engine.setProperty('voice',voices[1].id) # [0]for male voice
def wishme():
    speak("Welcome  Sir!")

def TakeCommand():
   r=sr.Recognizer()
   with sr.Microphone() as source:
      print("Listening....")
      r.pause_threshold = 0.7
      audio = r.listen(source)

   try:
     print("Recognizing....")
     query = r.recognize_google(audio, language='en-US')
     print(query)

   except  Exception as e:
     print(e)
     print("Say that again please")
     return "None"
   return query

def whatsapp_msg():
    speak("Can you please enter phone number of the person to whom you want to send message?")
    phone_no = input("Enter phone number: +91 ")
    phone_no = "+91" + str(phone_no)
    print(phone_no)

    speak("What message do you want to send?")
    msg = TakeCommand()
    print(msg)

    speak("When you want to send message (Now or Later)")
    print("When you want to send message (Now / Later)")

    msg_send_time = TakeCommand()

    if msg_send_time == "now":
         pywhatkit.sendwhatmsg_instantly(phone_no, msg, 15)
    else:
        speak("Enter the time when you want to send the message")
        speak("First Enter the time in hour")
        time_h = int(input("First Enter the time in hour: "))
        speak("Now Enter the time in minutes")
        time_m = int(input("Now Enter the time in minutes: "))

        pywhatkit.sendwhatmsg(phone_no, msg, time_h, time_m, 15)

    speak("Sending the message")
    print("Successfully Sent!")
    speak("Successfully Sent!")

Now we have successfully created the function. let us call the function

if __name__ == "__main__":
    wishme()
    while True:
        query = TakeCommand().lower() # to take command from user
        if 'whatsapp message' in query:
                whatsapp_msg()
Jiho Lee
  • 957
  • 1
  • 9
  • 24