我正在try 查找标题为"键入消息"的"div"元素.

以下代码起作用:

div_nodes = driver.find_elements_by_tag_name('div')
for element in div_nodes:
    if element.get_attribute('title') == 'Type a message':
        element.send_keys(Keys.ENTER)

但这不起作用:

element = driver.find_element_by_xpath('//div[@title="Type a message"]')
element.send_keys(Keys.ENTER)

我得到错误selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//div[@title="Type a message"]"}

编辑:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import urllib.parse

options = webdriver.ChromeOptions()
driver = webdriver.Chrome(executable_path=r'<mypath>/chromedriver.exe', options=options)
qry = {}
qry['phone'] = str(contact_number)
qry['text'] = message
url = "https://web.whatsapp.com/send/?{}".format(urllib.parse.urlencode(qry))
driver.get(url)
div_nodes = driver.find_elements_by_tag_name('div')
for element in div_nodes:
    if element.get_attribute('title') == 'Type a message':
        element.send_keys(Keys.ENTER)

推荐答案

我try 了这个xpath,它很有效

element = driver.find_element_by_xpath('//div[contains(@title, "message")]')

或者,您可以try 单击"发送"按钮

driver.find_element_by_css_selector('span[data-testid="send"]').click()

这对我也很有用.如果他们也为你工作,请告诉我.

p、 我建议使用新函数来更新代码,因为您正在使用的函数已经过时了.

from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service

driver = webdriver.Chrome(service=Service(r'<mypath>/chromedriver.exe'), options=options)

div_nodes = driver.find_elements(By.TAG_NAME, 'div')

element = driver.find_element(By.XPATH, '//div[@title="Type a message"]')

Python相关问答推荐

键盘.任务组

NumPy中的右矩阵划分,还有比NP.linalg.inv()更好的方法吗?

遵循轮廓中对象方向的计算线

覆盖Django rest响应,仅返回PK

从包含数字和单词的文件中读取和获取数据集

Pandas 除以一列中出现的每个值

如何使用没有Selenium的Python在百思买着陆页面上处理国家/地区 Select ?

大Pandas 胚胎中产生组合

如何在Python中将returns.context. DeliverresContext与Deliverc函数一起使用?

通过Selenium从页面获取所有H2元素

无法通过python-jira访问jira工作日志(log)中的 comments

try 将一行连接到Tensorflow中的矩阵

NumPy中条件嵌套for循环的向量化

移动条情节旁边的半小提琴情节在海运

如何启动下载并在不击中磁盘的情况下呈现响应?

lityter不让我输入左边的方括号,'

如何在达到end_time时自动将状态字段从1更改为0

如何创建引用列表并分配值的Systemrame列

在matplotlib中使用不同大小的标记顶部添加批注

polars:有效的方法来应用函数过滤列的字符串