Report this

What is the reason for this report?

TDD/CSS & HTML testing issue

Posted on May 13, 2020

Hello everyone - I just ran into another issue related to CSS selector especially ‘.has-error’ I still cant find a solution. Anyone here ever dealt with this issue before? pls kindly help. I am stuck at this point below:

‘’‘selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: .has-error’‘’

Related code between my template/selenium:

Python part:

            "You can't have an empty list item"))```

html part:

        <div class="form-group has-error">
                <span class="help-block">{{ error }}</span>
            </div>
 {% endif %}


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Never used it but most likely the selector returns a list and thus does not have a text field.

1. Ensure the Element is Visible and Rendered:

  • Make sure that the .has-error element is actually present in the HTML when Selenium is trying to locate it. This class may only appear conditionally (e.g., if there’s an error in the form), so the element may not always be there when the page first loads.

Try adding an explicit wait to ensure the element is fully loaded before Selenium attempts to locate it:

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

# Wait for the element with the .has-error class to appear
WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.CSS_SELECTOR, ".has-error"))
)

Check for Dynamic Content:

  • If .has-error appears dynamically (e.g., after form submission), ensure the error message is triggered properly before Selenium looks for the element. You can add an assertion or log step to confirm the flow is working as expected.

3. Check the Selector Syntax:

Ensure the CSS selector you’re using is correct. The correct syntax is:

driver.find_element_by_css_selector(".has-error")

If there are multiple .has-error elements on the page, you may want to use find_elements_by_css_selector and loop through them.

4. Check if it’s in an iFrame:

  • If the element is inside an iframe, Selenium can’t interact with it until you switch to the iframe. Check your HTML structure, and if it’s inside an iframe, you need to switch to it:
driver.switch_to.frame("frame_name_or_id")

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.