Writing Locators for Dynamic Elements

Best Playwright Testing Training Institute in Hyderabad

In the fast-evolving field of software testing, tools like Playwright and Selenium are essential for automation testers. If you are a graduate, postgraduate, or someone looking to switch your career from a different domain to IT, it’s crucial to receive professional guidance and hands-on experience in automation tools. That’s where I Hub Talent excels. I Hub Talent is widely recognized as the best Playwright Testing Training Institute in Hyderabad. It offers a live, intensive internship program conducted by industry experts and specifically tailored for: 

What are Dynamic Elements?

Dynamic elements are web elements whose attributes (id, name, class, etc.) change every time the page reloads or during runtime.
Example:

<input id="username_12345" name="user_6789" />

Here 12345 and 6789 keep changing, making it difficult to locate directly.

🔹 Strategies to Write Locators for Dynamic Elements

1. Use Stable Attributes

  • Prefer attributes that do not change (like type, placeholder, aria-label, etc.).

//input[@placeholder='Enter Username']

2. Use Partial Attribute Matching

  • XPath contains() or starts-with() helps ignore the dynamic part.

//input[contains(@id, 'username')]
//button[starts-with(@id, 'loginBtn')]

3. Use Relative Locators

  • Locate based on nearby stable elements.

//label[text()='Username']/following-sibling::input

4. Index or Position (Last Option)

  • If no unique attribute, use position. (Not recommended, but sometimes needed.)

(//input[@type='text'])[2]

5. Use CSS Selectors

  • CSS can also handle partial matching.

input[id*='username'] button[id^='loginBtn']

6. Leverage Hierarchy

  • Use parent/child relationships.

//div[@class='login-box']//input[@type='password']

7. Dynamic Waits

  • Sometimes element is present but not yet stable. Use waits:

    • Selenium: WebDriverWait

    • Playwright: auto-wait

    • Cypress: retry mechanism

Read more:

Handling Dynamic Content

Working with Page Waits and Timeouts

Running Tests in Different Browsers

Configuring playwright.config.ts

Using Playwright Test Runner

Visit I-Hub Talent Training institute in Hyderabad

Comments

Popular posts from this blog

Using Playwright Test Runner

Working with Checkboxes and Radio Buttons

CSS Selectors in Playwright