Search code examples
javaselenium-webdriverselenium-chromedriverbrowser-automationwebautomation

Not able to select radio button "NoSuchElementException: no such element: Unable to locate element" error is displayed


I'm trying to select a radio button from given 3 radio buttons but I'm getting No such element exception.

Here is the HTML code for all 3 radio buttons:

<div class="radioGroup">
<div>
    <div class="radio">
        <div class="radioVal"></div>
        <label><span><img src="https://s3.amazonaws.com/xyz.png" alt="AltText1">Radio Button1</span></label>
    </div>
    <div class="radio">
        <div class="radioVal"></div>
        <label><span><img src="https://s3.amazonaws.com/xyz1.png" alt="AltText2">Radio Button2</span></label>
    </div>
    <div class="radio">
        <div class="radioVal"></div>
        <label><span><img src="https://s3.amazonaws.com/xyz3.png" alt="AltText3">Radio Button3</span></label>
    </div>
</div>

I'm using this code to select radio button:

WebElement Radio2 = driver.findElement(By.xpath("//img[contains(@alt, 'AltText2')]"));
Radio2.click();

Solution

  • usually when this happens the cause is one of two reasons.

    1. The XPath is not correct
    2. You need to add a wait to your driver.findElement statement

    (1) To check if the XPath is correct

    1. Open Chromedriver and go to the website you are testing
    2. Press F12 to open the console (once open click the 'Console' tab)
    3. Type the following into the Chrome Browser Console and see if any objects are returned
    4. $x("//img[contains(@alt, 'AltText2')]")

    (2) Wait for element to be clickable

    System.TimeSpan timeToWait = new TimeSpan(0, 0, 10);
    WebDriverWait wait = new WebDriverWait(driver, timeToWait);
    IWebElement htmlElementOnPage = wait.Until(ExpectedConditions.ElementToBeClickable(By.XPath("//img[contains(@alt, 'AltText2')]")));
    

    Additionally, I don't see any radio buttons in your html. But I'm guessing you don't actually want to click on the label, but instead, you want to click on the above the label?

    If this is correct, your xpath should point to the div, not the label next to the div ...

    By.Xpath("//img[contains(@alt, 'AltText2')]/../div");