0

I am using Selenium and attempting to locate an element (table cell in a web app) by xpath. However, I am getting a NoSuchElementException when running my test cases.

I am positive that the xpath locator is correct, as I can paste it into my DOM and locate the element that way (it is also unique). I have also confirmed that the element is not in a different frame. Here is what my WebElement declaration looks like:

@FindBy(xpath = "//td[text()='info']//parent::tr//td[2]") WebElement txtInfo;

I can locate the element with this xpath locator in my DOM:

What possible reasons could there be for this error?

2

4 Answers 4

2

NoSuchElementException happens generally in 2 scenarios.

  1. Webelement locator is wrong. (which doesn't seems to be the situation in your case)
  2. Your are trying to find the webelement even before it is loaded on the page.(This seems to be your problem)

To solve this you should wait till the webelement gets loaded on to the webpage.

One way to do this to use WebDriverWait Class. Sample snippet is below:

/* Initialize the WebDriverWait, with 30 seconds of wait time. */
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("locator_name")));
1

There might be another reason why you get NoSuchElementException: you are not in the correct iframe. If your element is inside an iframe, you must "move" to it. See https://stackoverflow.com/questions/44834358/switch-to-an-iframe-through-selenium-and-python for an answer in python.

0

Note: I'm adding as an answer since I don't have the reputation to add a comment. Will edit the reply with an answer once you provide more details.



Coming to the question, would it be possible to check the same xpath with the Chrome developer tools Xpath search option in the Elements panel?

Also, if you can't share the application URL, it would be helpful if you can share the part of the code you are evaluating the xpath for - if possible, HTML for the table.

0

I learn selenium and faced with the same problem. Maybe this will help someone.

In my testcase selenium is clicking on a login button and a login page opens in a new tab. So, selenum could not find the element, because he still was looking on the first page. You need to switch him on the new opened tab (or window). Something like that:

    String currentTab = driver.getWindowHandle();
    Set<String> tabs = driver.getWindowHandles();

    for (String tab : tabs) {
        if (!currentTab.equals(tab)) {
            driver.switchTo().window(tab);
        }
    }

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.