【问题标题】:Send whatsapp message to contacts using Python but getting an error: InvalidSelectorException: Message: invalid selector: Unable to locate an element使用 Python 向联系人发送 whatsapp 消息但收到错误:InvalidSelectorException:消息:无效选择器:无法找到元素
【发布时间】:2019-09-19 00:54:30
【问题描述】:

我正在尝试使用 Python 向联系人发送 whatsapp 消息,但出现错误: 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)

我为此使用了 selenium,代码如下:

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()

我怎样才能做到这一点???

【问题讨论】:

  • 控制台中可能有一些字符。如果您使用硬编码路径会发生什么? '//span[@title = "Me Postpaid"]'

标签: python selenium selenium-webdriver selenium-chromedriver whatsapp


【解决方案1】:

click() 不返回任何内容。因此,您需要删除分配并正确替换代码行的格式:

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

与:

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

【讨论】:

  • 虽然是真的,但并没有回答主要问题InvalidSelectorException
  • 实际上我在代码中使用了正确的格式,粘贴时它就在这里了。但是使用上面的语句而不分配给user 工作。所以使用下面的语句,它现在可以工作了driver.find_element_by_xpath('//span[@title= "{}"]'.format(name)).click()谢谢你帮助我!!
  • @Guy ...它没有回答主要问题...,我们应该在该特定行中解决InvalidSelectorException的不同之处...有什么建议吗?
  • @DebanjanB 你可以看到我对这个问题的评论可能是因为原因,但是选择器中的空格是有效的,即使这不匹配任何东西。
  • @DebanjanB 不需要,他们是。它可能不匹配任何东西,但它仍然有效。
【解决方案2】:

可能是使用语音功能发送whatsapp消息或使用python而不使用selenium自动发送whatsapp消息的简单方法

首先

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

安装此 pip 模块后导入它们

import speech_recognition as sr 
import pywhatkit

发送whatsapp消息的主要语法是

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

第二次定义这样的函数:

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!")

现在我们已经成功创建了函数。让我们调用函数

if __name__ == "__main__":
    wishme()
    while True:
        query = TakeCommand().lower() # to take command from user
        if 'whatsapp message' in query:
                whatsapp_msg()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-24
    • 2021-04-05
    • 2023-03-28
    • 1970-01-01
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多