I'm trying to click on a radio button in selenium java but it's not clicking.
This is the inspect on the radio button:
<input name="timeSyncType" id="radioNTP" type="radio" ng-click="oSettingTimeInfo.szTimeMode='NTP'" ng-checked="oSettingTimeInfo.szTimeMode=='NTP'">
I tried this
WebElement radio = driver.FindElement(By.id("radioNTP"));
radio.click();
also I tried this
WebElement rbutton = driver.findElement(By.xpath("//input[@id='radioNTP']"));
rbutton.click();
but no luck, any help?
CodePudding user response:
To click on the element you can use either of the following locator strategies:
cssSelector:
driver.findElement(By.cssSelector("input#radioNTP[name='timeSyncType'][ng-click^='oSettingTimeInfo']")).click();
xpath:
driver.findElement(By.xpath("//input[@id='radioNTP' and @name='timeSyncType'][starts-with(@ng-click, 'oSettingTimeInfo')]")).click();
However, as the element is an Angular element so ideally to click() on the element you need to induce WebDriverWait for the elementToBeClickable() and you can use either of the following locator strategies:
cssSelector:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input#radioNTP[name='timeSyncType'][ng-click^='oSettingTimeInfo']"))).click();
xpath:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@id='radioNTP' and @name='timeSyncType'][starts-with(@ng-click, 'oSettingTimeInfo')]"))).click();
CodePudding user response:
Firs you will have to make sure that this id radioNTP
is unique in HTMLDOM or not.
Steps to check:
Press F12 in Chrome
-> go to element
section -> do a CTRL F
-> then paste the //input[@id='radioNTP']
and see, if your desired element
is getting highlighted with 1/1
matching node.
If yes, then there are quite a few ways to perform click in Selenium.
Code trial 1:
Thread.sleep(5);
driver.findElement(By.xpath("//input[@id='radioNTP']")).click();
Code trial 2:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@id='radioNTP']"))).click();
Code trial 3:
Thread.sleep(5);
WebElement button = driver.findElement(By.xpath("//input[@id='radioNTP']"));
((JavascriptExecutor)driver).executeScript("arguments[0].click();", button);
Code trial 4:
Thread.sleep(5);
WebElement button = driver.findElement(By.xpath("//input[@id='radioNTP']"));
new Actions(driver).moveToElement(button).click().build().perform();
If No, then you will have to change the locator and use the one which represent the desire node.
PS: Thread.sleep(5);
is just to solve this problem, if any of the above code works, Please replace the web element with WebDriverWait
.