Dynamic web elements are those whose attributes (like ID, name, or XPath) change during runtime. This makes it challenging to locate them reliably using static locators. Robot Framework, combined with SeleniumLibrary, provides several strategies to handle such elements:
1. Relative XPaths:
# Locate a stable ancestor element
${ancestor} Locator of stable ancestor
# Locate the dynamic element relative to the ancestor
${dynamic_element} XPath=//div[@id='${ancestor_id}']//button[contains(@class, 'dynamic-button')]
Click Element ${dynamic_element}
2. CSS Selectors with Partial Matching:
# If the class name changes but always contains 'product'
Click Element css=button[class*='product']
# Or if the ID always starts with 'item-'
Click Element css=div[id^='item-']
# Or if the ID always ends with '-details'
Click Element css=a[id$='-details']
3. Contains Text or Value:
Contains Text
or Element Should Contain
to locate it.Element Should Contain dynamic_element_locator Part of the stable text
4. Using Variables in Locators:
${product_id} Get Text product_id_element # Get ID dynamically
${locator} Set Variable id=product_${product_id}
Click Element ${locator}
5. Waiting Strategies:
Wait Until Element Is Visible
, Wait Until Page Contains Element
, Wait Until Element Is Enabled
Wait Until Element Is Visible dynamic_element_locator 5s Element not found after 5 seconds
Click Element dynamic_element_locator
6. Keyword Combinations:
${product_name} Get Text product_name_element
${locator} Set Variable xpath=//div[contains(@class, 'product')]//a[contains(text(), '${product_name}')]
Wait Until Element Is Visible ${locator}
Click Element ${locator}
7. Custom Locators (Advanced):
8. Test Data Setup: