I'm trying to capture the dynamic code using xpath(Selenium+Java).

I want to get that code and store it in a variable, but it always returns no such element exception.

My xpath looks like below when copied from browser:


How to resolve this issue

enter image description here

2 Answers 2


My xpath looks like below when copied from browser: //*[@id="__next"]/div[1]/div/main/div[2]/div/div[3]/div[2]/div/div[4]/dl/div[2]/dd/span

The xpath you mentioned has a high possibility to make your tests unstable. If the developer removes / changes any of the html attribute which form the xpath( for example removes div[4] from the DOM of your application ), it will result in the element not being found and eventually failure of the test. This might also explain the reason you received NoSuchElement exception.

A better approach would be to use relative xpath which has a less probability of getting changed. You can try to use this xpath: //span[text()='Code']/parent::dt/following-sibling::dd/span

To store the code into a variable, you can use:

String code = driver.findElement(By.xpath("//span[text()='Code']/parent::dt/following-sibling::dd/span")).getText();

In every application, such scenarios of retrieving dynamic runtime data through automation script is a common requirement. Usually any professional software testing services company, will handle such scenarios as utilities implemented in their automation frameworks by using parent-child locator concept.

Here also, we can use use the same parent-child locator concept using some unique element. In this case, unique element is "Code" and hence, correct xpath will be -

//dt//span[text() = 'Code']//..//dd//span

and then fetching the corresponding dynamic text using getText() default method of Selenium.

Additionally, below element will fetch you required dynamic code -

String codeToStore = driver.findElement(By.xpath("//dt//span[text() = 'Code']//..//dd//span")).getText();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.