使用 Python Selenium 的 WhatsApp Web 自动化(无法定位元素)

WhatsApp Web Automation with Python Selenium (unable to locate element)

我正在使用 python 和 selenium 向目标发送消息。

我可以成功打开 whatsapp 网页,但之后我无法打开我要向其发送消息的联系人的收件箱。

这是目前为止的代码。 第一部分很常见,我必须打开网页。它发生了没有任何问题。 下一部分是打开联系人以发送收件箱消息。 我为此尝试了两种不同的方法。他们都没有工作。

共同部分:

#WhatsApp Automation Project
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC 
from time import sleep

#Open WhatsApp web
driver =  webdriver.Chrome('D:/Drivers/chromedriver')
driver.get('https://web.whatsapp.com')


#The code should wait sometime for the user to scan the bar code.
sleep(15)
print('Code ended its pause.')

#chose whom to send messaage.
target = 'Name_in_Contacts'

#choose the message to send.
string = 'Guess who learned to autoate WhatsApp using Python.'

方法一:

# what I initially thought of doing

search  = driver.find_element_by_class_name("_3FeAD uu8jX")
#class_name is the name of the label of the search box in whatsapp web
#alternatively I had used class name('_3u328 copyable-text selectable-text') , a div class inside the  #label class\
#both the class name give the same error.
#check the image of the HTML code.
search.send_keys(target)

它给出错误:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"._3FeAD uu8jX"}
  (Session info: chrome=80.0.3987.132)

方法二: 此方法是从 Stack OverFlow 的一个解决方案中复制的。

#Stack OverFlow method. Didn't work.

#Open searcch box
search = WebDriverWait(driver,5).until(EC.presence_of_element_located((By.CLASS_NAME, "_3u328 copyable-text selectable-text")))
#Alternatively, the other class_name of label was also used.
#Both gave the same error.
search.send_keys(target)

它给出错误:

raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:

到现在一个多月了,还是解决不了问题

请不要关闭已经有人问过的问题。我知道关于这个主题有很多问题,但它们都不适合我,如果你能给我针对我的问题的解决方案,那将是很大的帮助。

提前致谢。

希望对您有所帮助。

element = wait.until(EC.visibility_of_element_located((By.XPATH, "//*[text()='Search or start new chat']/preceding-sibling::button]");
element.click();
//again wait  and then use sendkeys to select or search contact

终于找到答案了

我意识到打开搜索框没有意义。 在搜索框中输入姓名只会使姓名显示在顶部,不会 select 任何联系人。

我们应该在屏幕的左中找到联系人的姓名。

为此用途:

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

打开收件箱。

完成项目的 link 在这里: https://github.com/AshTiwari/WhatsApp-Automation-using-selenium-and-Python 请给个star,真的会鼓励我。