How can I handle checking the state of an element that is no longer valid on the webpage in my test script?

240    Asked by Deepabhawana in QA Testing , Asked on Apr 9, 2024

 I am currently engaged in a particular task that is related to testing a web-based application by using the selenium WebDriver in Java programming language. However, when I was going through with the process I encountered a scenario where I needed to verify the state of an element which became invalid due to the dynamic changes on the web-based page. How can I handle checking the state of an element that is no longer valid or even present on the web-based page in my test script?

Answered by Deepa bhawana

 In the context of Selenium, you can check the state of an element that becomes invalid or is no longer present on the web-based page due to the dynamic changes that involve handling the exceptions and using explicit is in the desired state before proceeding with verification or action. Here is an example given in Python:-

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

From selenium.common.exceptions import NoSuchElementException

# Initialize the WebDriver instance (assuming Chrome WebDriver)

Driver = webdriver.Chrome(executable_path=’path/to/chromedriver’)
Try:
    # Navigate to the webpage
    Driver.get(https://www.example.com)
    # Wait for the element to be visible using explicit wait
    Wait = WebDriverWait(driver, 10)
    Element = wait.until(EC.visibility_of_element_located((By.ID, “elementId”))) # Replace “elementId” with actual ID
    # Check the state of the element (e.g., enabled, disabled, visible, hidden)
    If element.is_enabled(): # Check if element is enabled
        Print(“Element is enabled.”)
    Else:
        Print(“Element is disabled or not visible.”)
Except NoSuchElementException:
    # Handle the case where the element is not found or is invalid
    Print(“Element not found or invalid. Handling the exception…”)
Finally:
    # Close the WebDriver instance
    Driver.quit()


Your Answer

Interviews

Parent Categories