My Java code includes a set of dynamically generated radio buttons using JavaScript that I am trying to interact with.
Despite attempting to use xpath to locate and click on one of the radio buttons, I keep receiving an error message:
Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element:
I have tried different methods like 'deliveryType' following Google Chrome's "Inspect elements," as shown below:
//WebElement deliveryType = driver.findElement(By.xpath("//div[contains(@id, 'checkout-shipping-method-load')]//*[contains(@name, 'shipping_method')]"));
//WebElement deliveryType = driver.findElement(By.cssSelector("[name='shipping_method'][id='s_method_matrixrate_matrixrate_5983']"));
//deliveryType.click();
Here is the inspected HTML element for the radio button:
<div id="checkout-shipping-method-load">
<dl class="sp-methods">
<dt>Select Shipping Method</dt>
<dd>
<ul>
<li>
<input name="shipping_method" type="radio" value="matrixrate_matrixrate_5983" id="s_method_matrixrate_matrixrate_5983" class="radio validation-passed">
<label for="s_method_matrixrate_matrixrate_5983">Standard Shipping<span class="price">NT$300</span></label></li>
<li>
<input name="shipping_method" type="radio" value="matrixrate_matrixrate_5991" id="s_method_matrixrate_matrixrate_5991" class="radio validation-passed">
<label for="s_method_matrixrate_matrixrate_5991">Express Shipping<span class="price">NT$1,200</span></label></li>
</ul>
</dd>
</dl>
</div>
Even after coding my script to click on the radio button using xpath, I still encounter the same element not found error.
How can I adjust my Selenium script to successfully interact with these dynamically generated radio buttons?
Should my xpath reference the raw JavaScript code or the HTML structure created by JavaScript after page load?
Your assistance is greatly appreciated.
Closed: I solved the issue by implementing an Implicit Wait to allow my JavaScript to run and render the HTML before interacting with it. I then used a List to store all radio buttons and accessed them by index.
Special thanks to Girish Sortur & JeffC.
Here is a snippet of my code:
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
List<WebElement> methods = driver.findElements(By.cssSelector("input[name='shipping_method']"));
methods.get(0).click();