Using Selenium with Python to detect and handle span error in a text box

While attempting to extract the error text from a span error box for the first name field when no name is entered and the user clicks on the submit button, I encountered an issue. The registration screen's HTML can be found at this link: . Instead of receiving the error text, I am getting 'none' as the output. In Chrome console, I tried using xpath "$x("//span[@class='span-error']")[2]" and css selector "$$(".span-error")[2]" to retrieve the text successfully. However, something seems to be missing in my script. Any guidance or suggestions would be greatly appreciated.

Test case:

  • Visit the provided link and leave the first name field empty to trigger a validation error. Verify the validation error message. Enter an invalid name like ":::" to trigger another validation error (there may be multiple). Test various scenarios.

https://i.sstatic.net/jwxJK.png

from time import sleep
from conftest import os
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains


# LoginScreenSelectors
sel_first_name = "#first-name-su"
sel_last_name = "#last-name-su"
sel_email = "#email-su"
sel_password = "#password-su"
sel_error_message = ".span-error:nth-of-type(2)"
sel_submit = f"""[data-automation-id="signup-submit-btn"]"""
sel_required_error = f"""[data-error="required"]"""


class Login():
    '''This will signup to the applcaiton '''

    def __init__(self, driver):
        self.driver = driver
        wait = WebDriverWait(self.driver, 20)
        self.first_name = wait.until(
            EC.presence_of_element_located((By.CSS_SELECTOR, sel_first_name))
        )
        self.last_name = wait.until(
            EC.visibility_of_element_located((By.CSS_SELECTOR, sel_last_name))
        )
        self.email = wait.until(
            EC.visibility_of_element_located((By.CSS_SELECTOR, sel_email))
        )
        self.password = wait.until(
            EC.visibility_of_element_located((By.CSS_SELECTOR, sel_password))
        )
        self.submit = wait.until(
            EC.visibility_of_element_located((By.CSS_SELECTOR, sel_submit))
        )

    def login_to_website(self):
        wait = WebDriverWait(self.driver, 10)
        print(self.driver.title)
        self.first_name.click()
        self.first_name.send_keys("  ")
        self.first_name.send_keys(Keys.TAB)

        self.first_name_error_message = wait.until(
             EC.presence_of_all_elements_located((By.CSS_SELECTOR, sel_error_message))
         )
        type(self.first_name_error_message)
        error_messages = []
        for messages in self.first_name_error_message:
            print(error_messages.append(messages.text))

        #if i could get this then i could simply get the first index and then keep filtering
         it but even that is proving to be difficult.

Answer №1

Give this a try to retrieve all elements containing error messages

errors = self.driver.find_elements(By.XPATH, "//*[@id="sign-up-form"]/div/span[2]']")

Answer №2

I found the solution by following these steps.

Start by obtaining the xpath as

f"""[data-error="required"]"""
and then use a loop to iterate through all error messages for input fields. This approach can be valuable for anyone attempting to validate positive and negative testing within the same test case.

from time import sleep
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

# LoginScreenSelectors
sel_first_name = "#first-name-su"
sel_last_name = "#last-name-su"
sel_email = "#email-su"
sel_password = "#password-su"
sel_submit = f"""[data-automation-id="signup-submit-btn"]"""
sel_required_error = f"""[data-error="required"]"""

class Register():
'''This wil register the user to the application '''

def __init__(self, driver):
    self.driver = driver
    wait = WebDriverWait(self.driver, 20)
    self.first_name = wait.until(
        EC.presence_of_element_located((By.CSS_SELECTOR, sel_first_name))
    )
    self.last_name = wait.until(
        EC.visibility_of_element_located((By.CSS_SELECTOR, sel_last_name))
    )
    self.email = wait.until(
        EC.visibility_of_element_located((By.CSS_SELECTOR, sel_email))
    )
    self.password = wait.until(
        EC.visibility_of_element_located((By.CSS_SELECTOR, sel_password))
    )
    self.submit = wait.until(
        EC.visibility_of_element_located((By.CSS_SELECTOR, sel_submit))
    )

def login_to_website(self):
    wait = WebDriverWait(self.driver, 10)
    '''Validate the inputs'''
    self.last_name.send_keys("Test Automation Last Name")
    self.email.send_keys("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="573617357934383a">[email protected]</a>")
    self.password.send_keys("password")
    self.submit.click()
    self.first_name_error_message = wait.until(
        EC.presence_of_all_elements_located((By.CSS_SELECTOR, sel_required_error))
    )
    for first_name_required_message in self.first_name_error_message:
        first_name_message = first_name_required_message.text.replace("\n", ":")
        # print(first_name_message)
        # print(first_name_message[first_name_message.find(":") + 1:])
    assert first_name_message[first_name_message.find(":") + 1:] == "First name is required."
    sleep(1)
    self.last_name.clear()
    self.first_name.click()
    self.first_name.send_keys("Test Automation First Name ")
    self.submit.click()
    self.last_name_error_message = wait.until(
        EC.presence_of_all_elements_located((By.CSS_SELECTOR, sel_required_error)))

    for last_name_required_message in self.last_name_error_message:
        last_name_message = last_name_required_message.text.replace("\n", ":")
        assert last_name_message[last_name_message.find(":") + 1:] == "Last name is required."

    self.email.clear()
    self.last_name.click()
    self.last_name.send_keys("Test Automation Last Name ")
    self.submit.click()
    self.email_error_message = wait.until(
        EC.presence_of_all_elements_located((By.CSS_SELECTOR, sel_required_error)))

    for email_required_message in self.email_error_message:
        email_message = email_required_message.text.replace("\n", ":")
        assert email_message[email_message.find(":") + 1:] == "Email address is required."

    self.password.clear()
    self.email.click()
    self.email.send_keys("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d4452484f7d58505c5451135e5250">[email protected]</a>")
    self.submit.click()
    self.password_error_message = wait.until(
        EC.presence_of_all_elements_located((By.CSS_SELECTOR, sel_required_error)))
    '''The only way I could verify it '''
    for password_required_message in self.password_error_message:
        password_message = password_required_message.text.replace("\n", " ")
        assert password_message[password_message.find("d") + 1:].replace(" ", "")  == "passwordisrequired."

    self.password.click()
    self.password.send_keys("something123$")
    self.submit.click()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Instead of displaying a preview of the file, the file upload with jQuery will now showcase the file link in a new window

I am currently working on a Jquery file upload project and I have decided not to use any plugins. My goal is to achieve this using Pure Jquery / JavaScript. Instead of previewing the file, I want to display a link (View) once the image or PDF is uploaded. ...

ElementNotInteractableException: Issue: The element cannot be accessed using the keyboard

I need help with using Selenium to input a snippet of JS code that I have in a form. Here is the code: <oj-input-password id="idcs-signin-basic-signin-form-password" data-idcs-placeholder-translation-id="idcs-password-placeholder" cl ...

The selenium module is struggling to locate the desired element

While attempting to download Instagram posts using the selenium module in Python, my code is functional but occasionally encounters errors. There are primarily two types of errors that appear: The first type stems from changes in the Instagram HTML code, ...

Unexpected Results from Div Positioning

Here is the PHP code snippet I am working on: <?php include 'header-adminpanel.php'; ?> <div class="container"> <div class="body-content"> <div class="side-left"><?php include 'adminproduct_sidebar.ph ...

What are the steps to add the Selenium IDE extension (selenium-ide-2.9.0.xpi) to Firefox version 45.0?

Encountering an issue while trying to install the Selenium IDE (selenium-ide-2.9.0.xpi). After clicking on the allow button, it starts downloading but even after it finishes, the Install button remains disabled. [] ...

Preventing Paste Function in Electron Windows

Currently, I am utilizing Electron and attempting to prevent users from pasting into editable content. While paste and match style remains enabled, the functionality is flawless on Mac devices. However, there seems to be an issue on Windows where regular ...

Is there a way to automatically resize the images on my navbar as the screen size decreases?

Is there a way to make the images in my navbar resize automatically so they remain next to each other instead of stacking on top of one another, especially when viewed on a mobile device where the navbar takes up a significant portion of the screen? Below ...

Scroll bar for multiple selection select tag without using div element (not supported in firefox)

.selector select[multiple="multiple"] { border-radius: 0; height: 200px; margin: 0 0 0 -1px; max-width: 368px !important; padding-left: 3px; width: 368px !important; } <select id="id_included_packages_from" class="filtered" multiple="multipl ...

Having trouble running the test method in TestNG due to an execution error

Within my TestNG automation framework, I am looking to implement the @AfterTest method in order to close a browser session by invoking a specific method from the customer's Util class. However, I encountered an error stating that "Parameter 'Webd ...

How can you confirm the presence of a specific word within a variable using Selenium?

I need assistance in verifying if a string contains a specific word using variables. Suppose I have a variable named options with the value "test,test2,test3". I want to check if this string includes the word test2. This is what I have attempted so far: ...

What causes the limitation of the div hover effect within the mat-grid-tile element?

When the user hovers over the mat-grid-tile, a div displays its content. However, I'm facing issues with the size of the div as it appears to be constrained within the mat-grid-tile. Here is how it looks before hovering: https://i.sstatic.net/Xqgdq.j ...

Execute protractor to open chrome in incognito mode and disable web security for cross-origin resource sharing

Our application performs well in production with CORS enabled. I am working on a project that is not CORS-enabled locally. Is there a way to disable web security for protractor? Can I modify the selenium instance by adding arguments? We are interested in ...

Activate a Dropdown Menu by Clicking in a React Application

I have a collapsible feature where you can click to expand or collapse a dropdown. Currently, the dropdown can only be clicked on where the radio button is located. I want the entire area to be clickable so that users can choose the dropdown by clicking an ...

Adjust the Division's Width to be 20% of the Total Page Width Excluding Margins

https://i.sstatic.net/T0nKq.png I need to create a menu page with 5 equal columns, but I'm facing an issue with the layout. Here's my current CSS for the yellow divs: width:20%; height:100vh; background-color: yellow; display:inline-block; In ...

Choose the appropriate data from the webpage based on the spreadsheet using Java with Selenium Webdriver

I am trying to extract data from a spreadsheet and populate the corresponding fields on a webpage. While I've been able to read the first and second columns successfully, I'm facing challenges with reading the third column and selecting values fr ...

What is the best way to incorporate custom CSS into an angular-fullstack application?

I'm interested in incorporating an image into a jumbotron and adjusting its width correctly, similar to what was discussed in this question: Bootstrap image to jumbotron width However, I am unsure of where to place my custom CSS code to achieve the d ...

Using jQuery to retrieve the tag name of the selected element

What is a simple method for retrieving a tag name? For instance, if I input $('a') into a function, how can I extract the tag name 'a'? ...

Leveraging the jQuery method .stop() to halt solely the .fadeTo() animation

My webpage features two jQuery effects applied to a <div>. Using the animate() function, I move it left and right, while utilizing fadeTo() to fade it out when the mouse is not hovering over the <div>. To prevent multiple fading effects caused ...

I can't understand why this question continues to linger, I just want to remove it

Is there a valid reason for this question to persist? I'm considering removing it. ...

Steps to eliminate the 'Edit Translation' text on Transposh

Attempting to eliminate the 'Edit Translation' text provided by Transposh to maintain the existing translations. Implementing CSS code like so: #transposh-3:nth-child(8){display:none;} and localizertextnode{display:none;} However, these styl ...