无法使用chrome驱动程序Python发送WhatsApp消息错误:NoSuchElementException



这是我在这里的第一篇文章!我正在使用Selenium的Chrome驱动程序向一些人发送WhatsApp附件。这是我的代码:

from selenium import webdriver
import os
from time import sleep
link="https://wa.me/91xxxxxxxxxx"
phnno="91xxxxxxxxxx"
driver=webdriver.Chrome(executable_path=f"{os.getcwd()}\chromedriver.exe")
#driver.get(link)
#button=driver.find_element_by_xpath('//a[@title="Share on WhatsApp"]')
#button.click()
driver.get(f"https://web.whatsapp.com/send?phone={phnno}&text&app_absent=0") 
#This above line opens up the sender window in whatsapp
attachbutt=driver.find_element_by_xpath('//span[@data-icon="clip"]') #This is line 15
#The above line is the one that is giving me the error
attachbutt.click()
sleep(10)
forpdf=driver.find_element_by_xpath('//input[@accept="*"]')
path="C:\Users\Deven\Desktop\test_file.pdf"
forpdf.send_keys(path) #Attaches the file
sleep(5)
sendbutt=driver.find_element_by_xpath('//span[@data-icon="send"]')
sendbutt.click()

错误:

DevTools listening on ws://127.0.0.1:56230/devtools/browser/1a8a2adb-37ee-4b0c-bedc-5cfb58559c24
Traceback (most recent call last):
File "d:CodingPython ScriptsDr Nikhil Prescription AppPrescription GeneratorWA-testing.py", line 15, in <module>
attachbutt=driver.find_element_by_xpath('//span[@data-icon="clip"]')
File "C:UsersDevenAppDataLocalProgramsPythonPython39libsite-packagesseleniumwebdriverremotewebdriver.py", line 394, in find_element_by_xpath
return self.find_element(by=By.XPATH, value=xpath)
File "C:UsersDevenAppDataLocalProgramsPythonPython39libsite-packagesseleniumwebdriverremotewebdriver.py", line 976, in find_element
return self.execute(Command.FIND_ELEMENT, {
File "C:UsersDevenAppDataLocalProgramsPythonPython39libsite-packagesseleniumwebdriverremotewebdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:UsersDevenAppDataLocalProgramsPythonPython39libsite-packagesseleniumwebdriverremoteerrorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//span[@data-icon="clip"]"}
(Session info: chrome=90.0.4430.212)
PS D:CodingPython ScriptsDr Nikhil Prescription AppPrescription Generator> [16176:15752:0523/212201.236:ERROR:device_event_log_impl.cc(214)] [21:22:01.236] USB: usb_device_handle_win.cc:1054 Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F)

它说它无法定位元素,但我在检查网站和编写代码时非常小心。尽管如此,我还是想知道为什么它不起作用。有人能帮我做些什么吗?非常感谢。

在单击该元素之前,似乎缺少一个等待/延迟
最简单的解决方案是放置

sleep(5)

之前

attachbutt=driver.find_element_by_xpath('//span[@data-icon="clip"]')

然而,在那里使用预期的条件要好得多。像这样:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
attachbutt = WebDriverWait(driver, 20).until(
EC.element_to_be_clickable((By.XPATH, '//span[@data-icon="clip"]')))

最新更新