Utilizing selenium to interact with JavaScript-generated radio buttons

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();

Answer №1

If you're looking to interact with a dynamic element, the key is to patiently wait for it to show up. In Selenium, you can achieve this by using the WebDriverWait() method. The ExpectedConditions in Selenium are there to help you verify expectations, like checking for element visibility before proceeding. Here's an example code snippet -

WebElement radioBtn = driver.findElement(By.xpath("//input[@id='s_method_matrixrate_matrixrate_5983']"));
new WebDriverWait(driver,10).until(ExpectedConditions.visibilityOf(radioBtn));

Another approach is to use FluentWait, which offers flexibility in waiting for elements to appear. Here's how you can implement it -

new FluentWait<WebElement>(radioBtn).
    withTimeout(50, TimeUnit.SECONDS).
    pollingEvery(2,TimeUnit.SECONDS);

With FluentWait, you can specify the conditions and intervals for waiting for an element to be visible. Adjust the polling frequency based on how often you expect the element to appear. Set the timeout according to the maximum time it should take for the element to show up in the DOM. I hope this explanation clarifies things.

Answer №2

To efficiently handle the shipping method options, I would gather all the INPUT elements related to shipping methods and store them in a collection called methods. Afterwards, I can easily select and click on the specific method needed. See the provided sample code snippet for reference.

List<WebElement> methods = driver.findElements(By.cssSelector("input[name='shipping_method']"));
methods.get(0).click(); // This action clicks on the first element, denoted as Standard Shipping

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Selenium is unable to find the element

I'm new to Python and I've created a script to automatically log in to the website, . The problem is that while selenium successfully launches Firefox, it doesn't proceed to enter my email and password. from selenium import webdriver from s ...

Is there a way for me to initiate another joyride adventure?

Encountering a challenge with my joyride tour - after completing one tour, I aim to commence a second. Despite attempting to trigger the second tour in the postRideCallback function, I find myself stuck in a loop with the first tour. Seeking guidance on re ...

Transfer photos and videos to an external server using Javascript with Meteor framework

I currently have a meteor application hosted on Digital Ocean. I am considering setting up a dedicated server to store all images and videos separately from the site itself. Whenever a user uploads new media, it will be saved to this separate server. Does ...

Does HtmlUnitDriver have a void in HTTP Components?

Getting started with Selenium 2 and the HtmlUnitDriver, I set up a test project. Everything works perfectly when using the FirefoxDriver. However, when I switch to the HtmlUnitDriver, I encounter the following exception. Could it be that I am missing some ...

Standardize API data for utilization in Redux

I have an API that provides the following data: const data = { id: 1, name: 'myboard', columns: [ { id: 1, name: 'col1', cards: [ { id: 1, name: 'card1' }, { id: 2, name: 'card ...

What is the best time to fetch the height of an element containing an image?

I am working on my web app and I want to implement a popup element that contains an <img> element. Typically, the image source is larger than necessary, so I resize it using CSS. However, before displaying the popup, I need to determine its outerHeig ...

Anticipated the start of an array but encountered a string instead on line 1, character

Exploring Java/Android as a beginner, I am attempting to create a class that queries basic REST JSON data from the URL . Here is a sample of the JSON response received: { "cep": "69050-110", "logradouro": "Conjunto Tocantins", "complemento": "", " ...

Creating nested routes in react-router is a useful technique for managing complex applications. By

I have a parent container with nested routes: function Home() { render ( <Router> <Switch> <Route exact path="/website" component={Website} /> <Route path="/dashboard" compo ...

Troubleshooting chromedriver error messages in the console tab

I executed my test script and encountered an error message in the console tab: "ChromeDriver version 84.0.4147.30 (48b3e868b4cc0aa7e8149519690b6f6949e110a8-refs/branch-heads/4147@{#310}) is running on port 30846 with only local connections allowed. ...

Strategies for avoiding asynchronous behavior in AJAX with JQuery

My questions are best explained through code rather than words. Take a look at the snippet below and try to understand it: $('#all').on('change', function(){ //ONCHANGE RADIOBUTTON, THERE ARE #bdo, #cash also. $.ajax({ type:"GET", ...

Unable to specify file for upload in Selenium for Edge browser

Through extensive research, I have come to the conclusion that Microsoft developers do not support the sendKeys(...) function on file inputs when using Selenium Java on MS Edge. Unfortunately, this means I may not be able to effectively test file uploadin ...

The dynamic styles set by CSS/JavaScript are not being successfully implemented once the Ajax data is retrieved

I am currently coding in Zend Framework and facing an issue with the code provided below. Any suggestions for a solution would be appreciated. The following is my controller function that is being triggered via AJAX: public function fnshowinfoAction() { ...

Looking to retrieve serialized data from a form

I'm a beginner with prototypejs and I need assistance in extracting serialized values from a submitted form using Ajax in prototype. Can anyone provide guidance on this? ...

Switch focus between two text fields

Within my react application, I have a total of 10 material-UI textfields. The initial 8 textfields are contained within an expansion panel, while the remaining two textfields are housed in another expansion panel. I am seeking to set up a system where auto ...

How to manage UNC paths and "mapped network drives" within an Electron application?

I have developed a cross-platform (macOS-Windows) app using Electron that functions smoothly with files and media assets from a local drive. However, it encounters issues when dealing with UNC paths and "mapped network drives". Since I am a contractor, I d ...

The lifecycle methods in React consistently return the same props when updating the date

An interesting issue has emerged in a component that receives new props. The peculiar behavior involves the reception of an Object and a date object. Upon updating the object, in componentWillUpdate(nextProps, nextState), it is observed that nextProps.som ...

I am constantly encountering this issue: Uncaught TypeError - It's impossible to read properties of undefined (specifically 'image') in PromptCard at PromptCard.jsx on line 37

Click here to see the error message This is the code for my components\PromptCard.jsx file: "use client"; import { useState } from "react"; import Image from "next/image"; import { useSession } from "next-auth/reac ...

Tips on handling parameters in the form of a single value or an array of values

I've implemented multiple functions structured like this: this.something = function (which) { // Can be one or many. if (!Array.isArray(which)) { // Single input case. doSomething(which); } else { ...

Issues with invoking JavaScript functions

In my HTML page, I'm calling a function from a separate .js file named jQuery.loadjson.js. The syntax being used is $('#data').loadJSON(data); #data refers to a div element, and data is a JSON object. However, when I try to debug this in Fi ...

AngularJS: Showcase HTML code within ng-view along with its corresponding output displayed in a navigation format such as Html, Css, JS, and Result

Currently, I am working on a web application. One of the screens, screen-1, consists of a series of buttons labeled 'Code'. When a user clicks on any of these buttons, it loads a different HTML page, screen-2, in the ng-view using $location.path( ...