简体   繁体   中英

How to select radio button using Selenium WebDriver with Java?

Hello I am trying to select a radio button using a for but I can not seem to be able to select a radio button if you guys can show me how this works by selecting any one of the radio buttons above that would be really helpful and show me the the way i do it with these radio buttons etc.

Thank you very much!

HTML:

<span class="radioButtonHolder">
<input type="radio" name="R001000" value="1" id="R001000.1" class="customCtrlLarge" />
</span>
<label for="R001000.1">Test 1</label>
</div>
<div class="Opt2 rbloption">
   <span class="radioButtonHolder">
   <input type="radio" name="R001000" value="2" id="R001000.2" class="customCtrlLarge" />
   </span>
   <label for="R001000.2">Test 2</label>
</div>

Java code:

List<WebElement> RadioGroup1 = driver.findElements(By.name("R001000"));

     for (int i = 0; i < RadioGroup1.size(); i++) {
       System.out.println("NUM:" + i + "/" + RadioGroup1.get(i).isSelected());
}

RadioGroup1.get(1).click();

The error code:

Started InternetExplorerDriver server (32-bit)
2.44.0.0
Listening on port 30883
NUM:0/false
NUM:1/false
NUM:2/false
Exception in thread "main" org.openqa.selenium.ElementNotVisibleException: Cannot click on element (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 91 milliseconds
Build info: version: '2.44.0', revision: '76d78cf', time: '2014-10-23 20:02:37'
System info: host: 'Code-PC', ip: 'Nope', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_31'
Driver info: org.openqa.selenium.ie.InternetExplorerDriver
Capabilities [{browserAttachTimeout=0, enablePersistentHover=true, ie.forceCreateProcessApi=false, ie.usePerProcessProxy=false, ignoreZoomSetting=false, handlesAlerts=true, version=11, platform=WINDOWS, nativeEvents=true, ie.ensureCleanSession=false, elementScrollBehavior=0, ie.browserCommandLineSwitches=, requireWindowFocus=false, browserName=internet explorer, initialBrowserUrl=http://localhost:30883/, takesScreenshot=true, javascriptEnabled=true, ignoreProtectedModeSettings=false, enableElementCacheCleanup=true, cssSelectorsEnabled=true, unexpectedAlertBehaviour=dismiss}]
Session ID: cebed22f-5ae6-464b-bb1b-a18150f9e5a8
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:204)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:156)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:599)
    at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:268)
    at org.openqa.selenium.remote.RemoteWebElement.click(RemoteWebElement.java:79)
    at javaapplication4.JavaApplication4.main(JavaApplication4.java:59)

I am using three attributes here. type would make sure it only returns the radio button, name will filter more to find make sure it finds the element with matching names only and then id to uniquely identify it. Notice you can use cssSelector as [id='R001000.1'] . I am just showing you different possibilities.

CssSelextor for first radio

[name='R001000'][id='R001000.1'][type='radio']

CssSelector for second radio

[name='R001000'][id='R001000.2'][type='radio']

Implementation:

By byCss = By.cssSelector("[name='R001000'][id='R001000.2'][type='radio']");
driver.findElement(byCss).click();

I do not suggest you to use for loop for this kind of scenario. Issue is there could be more than expected number of radio button/element hidden with same name so the list will return you everything.

After the discussion with OP the following code sample was suggested:

public void Test()
{
    _driver = new FirefoxDriver();
    _driver.Navigate().GoToUrl(Url);
    _driver.Manage().Window.Maximize();
    _driver.FindElement(By.Id("CN1")).SendKeys("7203002");
    _driver.FindElement(By.Id("CN2")).SendKeys("0370");
    _driver.FindElement(By.XPath("//*[@id='InputDay']/option[@value='23']")).Click();
    _driver.FindElement(By.XPath("//*[@id='InputMonth']/option[@value='02']")).Click();
    _driver.FindElement(By.XPath("//*[@id='InputYear']/option[@value='15']")).Click();
    _driver.FindElement(By.Id("NextButton")).Click();
    _driver.FindElement(By.XPath("//label[.='Lunch']//../span")).Click();
    _driver.FindElement(By.XPath("//label[.='Dining room']//../span")).Click();

}

Try this

List<WebElement> elements = driver.findElements(By.xpath("//input[@class='customCtrlLarge']");
for(WebElement element : elements){
if(!element.isSelected()){
    element.click();
}
}

Let me know if it works

Its getting timeout in 91 milliseconds which is less than second! I don't see any issue with original code. I suspect its a synchronization issue, try adding implicit wait. see if that works.

driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM