Skip to main content
 首页 » 编程设计

c#之在第一个 ul 和它的第一个 li 中获取第一个输入

2024年02月23日19xing901022

这是标记:

<h3>Customers</h3> 
   <ul> 
      <li> 
          <label for="customer115">Some Customer Name</label> 
          <input id="customer115"  type="checkbox" value="115" name="customer115"> 
      </li> 
      .. there are more <li> here...and so on 
   </ul> 
<h3>Dealers</h3> 
   <ul> 
      <li> 
          <label for="dealer100">Some DealerName</label> 
          <input id="dealer100"  type="checkbox" value="115" name="dealer115"> 
      </li> 
      .. there are more <li> here...and so on 
   </ul> 

例如,我正在尝试获取对客户复选框的引用,以便我可以通过 XPath 在其上执行 click()。我在 Selenium 中执行此操作,例如:

 string sXPath = string.Format(string.Format("//h3[text()='{0}']/ul/li/input[1]", "Customers")); 
 
IWebElement firstCompanyCheckbox = GetElementByXPath(sXPath); 
firstCompanyCheckbox.Click(); 

到目前为止我不知道如何得到这个引用,上面的 xPath 没有找到它。我想点击那个复选框。

请您参考如下方法:

ul 不是 h3 的子级。这是一个 sibling 。调整您的 XPath 以使用 following-sibling:: axis

//h3[text()='{0}']/following-sibling::ul/li/input[1] 

如果要确保选择第一个 ul 和第一个 li,则添加额外的谓词过滤器:

//h3[text()='{0}']/following-sibling::ul[1]/li[1]/input[1]