我有这个HTML
<div class="Radio">
<label>
<input class id="checkbox" name="category" type="radio" value="1">
<strong> TONY STARK </strong>
</label>
<label>
<input class id="checkbox" name="category" type="radio" value="2">
<strong> IRON MAN </strong>
</label>
<label>
<input class id="checkbox" name="category" type="radio" value="3">
<strong> ROBERT DOWNEY </strong>
</label>
当用户将其作为灵活参数传递时,我需要选择基于TONY STARK
,IRON MAN
,ROBERT DOWNEY
的单选按钮
我试过这个,但任何其他简单的方法肯定会帮助我!
driver.FindElement(By.Id("checkbox"));
for(WebElement radiobutton: radiobuttons)
{
if(radiobutton.getAttribute("value").equals("TONY STARK"))
radiobutton.click();
}
您应该尝试使用Xpath
获取单个单选按钮并避免循环如下: -
string Xpath = ".//input[following-sibling::strong[contains(.,'TONY STARK')]]";
要么
string Xpath = ".//label[contains(.,'TONY STARK')]/input";
使用这些Xpath
中的任何一个来找到单选按钮:
var radio = driver.FindElement(By.Xpath(Xpath));
radio.Click();
您可以使用xpath来执行此操作。试试下面的xpath .//label[contains(text(),'TONY STARK')]/input[@id='checbox']
使用带索引的XPath识别单选按钮
IWebElement radioButton = driver.FindElement(By.XPath("//*[@type='radio'][1]");
radioButton.Click();
哪里:
星号*表示通配符。
[1]是单选按钮选项的位置(“TONY STARK”)
从现在开始创建一个包装无线电的类:
public class RadioButtons
{
public RadioButtons(IWebDriver driver, ReadOnlyCollection<IWebElement> webElements)
{
Driver = driver;
WebElements = webElements;
}
protected IWebDriver Driver { get; }
protected ReadOnlyCollection<IWebElement> WebElements { get; }
public void SelectValue(String value)
{
WebElements.Single(we => we.GetAttribute("value") == value).Click();
}
}
然后你可以像这样使用它:
RadioButtons categories = new RadioButtons(Driver, driver.FindElements(By.Name("category")));
categories.SelectValue("TONY STARK");