首页 > 解决方案 > 单击按钮但 Python Selenium 仍引发“无法定位元素”错误

问题描述

我正在尝试按下 HTML 是这样的网站的确认按钮

<footer>
    <button class="button btn-default page-container__footer-button" data-testid="page-container-footer-cancel" role="button" tabindex="0">Reject</button>
    <button class="button btn-primary page-container__footer-button" data-testid="page-container-footer-next" role="button" tabindex="0">Confirm</button>
</footer>

我使用以下代码单击确认按钮:

driver.find_element_by_xpath('//*[@id="app-content"]/div/div[3]/div/div[3]/div[3]/footer/button[2]').click()

应该是这样,Selenium 单击了 Confirm Button,但仍然错误抛出此错误,并且由于哪个程序停止。

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="app-content"]/div/div[3]/div/div[3]/div[3]/footer/button[2]"}

我知道我可以使用 except 语句,但我不想使用它,而是想修复错误。

提前致谢

标签: pythonselenium

解决方案


您使用的绝对 xpath本质上可能很脆弱,如果Confirm文本是按钮的静态文本,您可以使用text自身在 HTMLDOM 中表示它。

//button[text()='Confirm']

在 Selenium 中有 4 种点击方式。

我将使用这个 xpath

//button[text()='Confirm']

代码试用1:

time.sleep(5)
driver.find_element_by_xpath("//button[text()='Confirm']").click()

代码试用2:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[text()='Confirm']"))).click()

代码试用3:

time.sleep(5)
button = driver.find_element_by_xpath("//button[text()='Confirm']")
driver.execute_script("arguments[0].click();", button)

代码试用4:

time.sleep(5)
button = driver.find_element_by_xpath("//button[text()='Confirm']")
ActionChains(driver).move_to_element(button).click().perform()

进口:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains

PS:如果我们有唯一的条目,请检查dev tools(谷歌浏览器)。HTML DOM

检查步骤:

Press F12 in Chrome-> 转到element部分 -> 执行CTRL + F-> 然后粘贴xpath并查看,如果您想要element的是否使用匹配节点突出显示。1/1

请注意,这是一个假设button不在iframe/frameor中shadow root

更新 :

滚动到底部:

driver.execute_script("var scrollingElement = (document.scrollingElement || document.body);scrollingElement.scrollTop = scrollingElement.scrollHeight;")

推荐阅读