NoSuchElementException:消息:尝试使用 Selenium 和 Python 定位元素时无法定位元素

NoSuchElementException: Message: Unable to locate element while trying to locate an element using Selenium and Python

我有一个无法使用 Python Firefox Selenium 访问的特定登录按钮。这是此网页上的登录按钮:https://schalter.asvz.ch/tn/lessons/39616

我是 运行 Ubuntu 16.04,Python 3.5.2,Firefox 65.0 和 Selenium 3.141。

我尝试了在 Whosebug 上找到的几种方法组合,包括以下内容:

login = driver.find_element_by_xpath("//*[@class='btn btn-default ng-star-inserted']")

login = driver.find_element_by_xpath("//button[@class='btn btn-default ng-star-inserted']")

login = driver.find_element_by_class_name('btn btn-default ng-star-inserted')

login = driver.find_element_by_xpath("//*[contains(., 'Login')]")

login = driver.find_element_by_name('app-lessons-enrollment-button')

但其中 none 有效。总是导致:

NoSuchElementException: Message: Unable to locate element: //*[@class='btn btn-default ng-star-inserted']

这个按钮有什么不同?我怎样才能让它发挥作用?

试试下面的选项。

Login=driver.find_element_by_css_selector("button.ng-star-inserted")

或者试试这个

WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.CSS_SELECTOR,'button.ng-star-inserted'))).click()

选项 2 需要以下导入。

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

试试下面的 xpath:

xpath = "//button[@title='Login']"
element = driver.find_element_by_xpath(xpath);
element.click();

遵循 xpath 工作正常(使用 selenium java 测试)

//button[@title='Login']

我能够找到并单击该按钮。

这个错误信息...

NoSuchElementException: Message: Unable to locate element: //*[@class='btn btn-default ng-star-inserted']

...表示 ChromeDriver 无法通过您使用的定位器找到所需的元素。


实际上,您的前两 (2) 个定位器非常完美。

然而,所需的元素是 Angular element so to locate the element you have to induce WebDriverWait for the element to be clickable and you can use either of the following :

  • 使用CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.btn.btn-default.ng-star-inserted[title='Login']"))).click()
    
  • 使用 XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='btn btn-default ng-star-inserted' and @title='Login']"))).click()
    
  • 注意:您必须添加以下导入:

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