我使用 selenium IDE 来跟踪我的 UI 活动。我从 IDE 获得了以下代码,并且也在 UI 中进行了检查,但是在通过 id 使用 find_element 时,我收到了 css 选择器错误。
driver.find_element(By.ID, "button-1034-btnIconEl").click()
错误是
引发异常类(消息,屏幕,堆栈跟踪) NoSuchElementException:没有这样的元素:无法找到元素: {"method":"css 选择器","selector":"[id="button-1034-btnIconEl"]"}
(会话信息:chrome=78.0.3904.108)
请帮我调试这个..
要在
按钮上使用文本为添加订单的
click()
,您必须为element_to_be_clickable()
诱导WebDriverWait,您可以使用以下任一定位器策略:
使用
CSS_SELECTOR
:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a[id^='button-'] > span.x-btn-wrap > span.x-btn-button > span.x-btn-inner.x-btn-inner-center"))).click()
使用
XPATH
:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[starts-with(@id, 'button-')]/span[@class='x-btn-wrap']/span[@class='x-btn-button']/span[@class='x-btn-inner x-btn-inner-center' and contains(., 'Add')]"))).click()
注意:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
使用Chrome时,可以在Selenium“selenium.common.exceptions.NoSuchElementException”中找到关于
NoSuchElementException: no such element
的详细讨论
id 似乎是动态的,所以你不能在选择器中使用静态 id。为此,您需要使用动态 xpath。
您可以使用以下xpath:
driver.find_element(By.XPATH, "//span[contains(@id,'btnIconEl')]").click()
或
您也可以在 xpath 中使用其文本找到该元素:
driver.find_element(By.XPATH, "//span[contains(text(),'Add Order')]").click()
可能不是你的情况,但我犯了一个愚蠢的错误,导致了这个错误。 我忘记使用以下行获取实际网页:
driver.get(my_link)
因此,我得到了同样的错误
我有同样的错误 ) selenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:无法定位元素:{“method”:“css选择器”,“selector”:“[id =“textfield-2e63j8j”]“} (会话信息:chrome=118.0.5993.118);有关此错误的文档,请访问:https://www.selenium.dev/documentation/webdriver/troubleshooting/errors#no-such-element-exception