Search code examples
pythonselenium-webdrivercss-selectorsclassnamenosuchelementexception

Python Selenium Unable to locate element [NoSuchElementException] when using CLASS_NAME selector


When I try to use find_element(By.CLASS_NAME, 'classname'), it will always return NoSuchElementException, unable to locate element. But when I use ID and NAME on the same element, it worked! Only CLASS_NAME failed.

Here is the HTML

<input type="text" name="login" id="login_field" class="form-control input-block js-login-field" autocapitalize="off" autocorrect="off" autocomplete="username" autofocus="autofocus">

And here is the script

username1 = driver.find_element(By.CLASS_NAME,"form-control input-block js-login-field")
username2 = driver.find_element(By.ID,"login_field")
print(username1)
print(username2)

Username1 failed, username2 pass.

I tried change to cssSelector:

username1 = driver.findElement(By.cssSelector("input.form-control input-block js-login-field"));

I also tried change syntax:

username1 = driver.find_element(By.CLASS_NAME("input[class='form-control input-block js-login-field']"))

But none of it works.


Solution

  • The By.CLASS_NAME method in Selenium is designed to work with a single class name, not multiple.

    The element has multiple classes: form-control, input-block, and js-login-field. You should select one of these classes to use with By.CLASS_NAME.

    username1 = driver.find_element(By.CLASS_NAME, "form-control")
    

    Using By.CSS_SELECTOR for a Compound Class Name

    username1 = driver.find_element(By.CSS_SELECTOR, ".form-control.input-block.js-login-field")