简体   繁体   English

如何使用带有Java的Selenium WebDriver选择单选按钮?

[英]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. 您好,我正在尝试使用for选择一个单选按钮,但是如果你们可以通过选择上面的任何一个单选按钮来向我展示其工作原理,那么我似乎无法选择一个单选按钮并显示我用这些单选按钮等操作的方式。

Thank you very much! 非常感谢你!

HTML: 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: Java代码:

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. type将确保仅返回radio按钮, name将进行更多过滤以查找,确保其仅找到具有匹配名称的元素,然后使用id进行唯一标识。 Notice you can use cssSelector as [id='R001000.1'] . 请注意,您可以将cssSelector用作[id='R001000.1'] I am just showing you different possibilities. 我只是向您展示不同的可能性。

CssSelextor for first radio 第一次广播的CssSelextor

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

CssSelector for second radio 第二个收音机的CssSelector

[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. 我不建议您在这种情况下使用for循环。 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: 与OP讨论之后,建议使用以下代码示例:

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! 它的超时时间为91毫秒,不到秒! 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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