Skip to main content
 首页 » 编程设计

c#之在 Selenium Webdriver [C#] 中选择单选按钮

2024年02月05日33lonelyxmas

我有这个 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();