首页 > 解决方案 > selenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:无法找到元素:-下拉项目 ID,XPATH 不起作用

问题描述

有人可以帮我解决这个问题吗?

这是网站中的元素部分: <span id="__xmlview0--__idDateType-arrow" class="sapMSltArrow"></span>

这是我在 python 脚本中的查找元素部分:

driver.find_element_by_xpath("//*[@id='__xmlview0--__idDateType-arrow']").click()

错误信息:

selenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:无法找到元素:{"method":"xpath","selector":"//*[@id='__xmlview0--__idDateType-arrow']" (会话信息:铬=92.0.4515.159)

编辑 :

<div id="_xmlview0--__idDateType" data-sap-ui="__xmlview0--__idDateType" style="width:100%;max-width:100%" class="sapMSlt sapMSltDefault sapMSltHoverable sapMSltWithArrow" aria-required="true" aria-labelledby="__xmlview0--filbar-filterItem-___INTERNAL-MyOwnFilterField __xmlview0--__idDateType-label" role="combobox" aria-expanded="false" aria-live="polite" tabindex="0"><label id="__xmlview0--__idDateType-label" for="__xmlview0--__idDateType" class="sapMSltLabel">Fiscal Year</label><span id="__xmlview0--__idDateType-arrow" class="sapMSltArrow"></span></div>

标签: pythonselenium

解决方案


这个例外

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: 

暗示其中之一element locator is not correct,,,,element is not rendered properlyelement is in iframe.

下面的详细说明

  1. 元素locator不是,或者 是通过使用框架由服务器获取的。correctElement is dynamic in nature i.e. element locator idclass_namegeneratedjavascript

解决方案

尝试使用reliable locator. 可能有一个稳定的 preceding-siblingor following-siblingor or ancestorordescendant节点。并基于提到的节点,尝试使用 xpath 到达所需的元素。

HTML DOM如果我们想要与之交互的元素有唯一的条目,请务必签入。

检查步骤:-

按下F12- Chrome> 转到element部分 -> 执行CTRL + F-> 然后粘贴定位器,然后查看所需元素是否突出显示,如果突出显示,我们是否有唯一的条目 1/1 ?

  1. 元素未rendered completely/partial加载,您正在尝试与之交互。

解决方案

基本上,在这里睡觉会帮助我们。您可以尝试将其放在time.sleep(5)这里进行调试,如果可行,则稍后可以通过Explicit waits.

例子 :-

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, ""))).click()

进口:-

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
  1. 元素在iframe/frame/frameset

解决方案

检查任何iframe可能是parent/ancestor node我们node想要与之交互的内容。如果碰巧是,您需要switch the driver focus to iframe first然后可以与所需的元素进行交互。

切换到 iframe 的代码:

WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, "")))

切换到 iframe 后,您可以与上面提到的driver.find_element或者进行交互。Explicit waits

此特定票证的实际问题:

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

推荐阅读