python - 单击按钮但 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 语句,但我不想使用它,而是想修复错误。
提前致谢
解决方案
您使用的绝对 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/frame
or中shadow root
。
更新 :
滚动到底部:
driver.execute_script("var scrollingElement = (document.scrollingElement || document.body);scrollingElement.scrollTop = scrollingElement.scrollHeight;")
推荐阅读
- css - masonry - 如果页面调整大小,则在一列中显示图像
- docker - 如何将本地镜像推送和部署到 Kubernetes
- c - 如何修复“Gtk-WARNING ** 使用标题栏添加到对话框操作区域的内容”
- c# - 使用 Fopen 读取 C 中的文件并从中获取特定值
- javascript - 在 JavaScript 的严格模式下,为什么读取仅设置的属性不是错误?
- symfony - Symfony 4 - 如何在其他控制器页面上打印表单输入?
- javascript - 来自服务器页面的 Google Map JavaScript API:路线服务:此 API 项目无权使用此 API
- sql - 如何在 Oracle 表的 varchar 列中的第二个和第四个字符之后插入“/”
- python - 在 if 条件中附加列表
- usage-statistics - 将页面浏览量存储为 cookie - 好主意?