c# - Selenium/Chrome - 选择没有 ID 的复选框输入

标签 c# selenium selenium-webdriver xpath selenium-chromedriver

提前感谢您的帮助。 Selenium/Chrome 的新手,在我遇到特定场景之前已经很好地运行了它。

我有一个包含 5 个字段的模态(3 个下拉菜单和一个带有 2 个 LI 的 UL)

每个 LI 包含一个标签和输入复选框。

所有下拉菜单都有一个 Id,因此它们很容易通过 FindElement(By.Id("ID")).SelectText("TEXT");

操作

但是 Ul 中的 Li 没有它们,我在每次尝试定位它们时都遇到了 NoSuchElementExceptions。

<ul id="CertificatesToAdd" name="CertificatesToAdd" class="nav nav-list 
    checkbox-list add-certificate-required" data-trigger="manual" data- placement="top">
  <li>
    <label class="checkbox" style="font-weight:normal !important;">
    <input type="checkbox" class="add-certificate-checkbox" 
    value="171">
    Certificate of Registration
    </label>
  </li>
  <li>
    <label class="checkbox" style="font-weight:normal !important;">
    <input type="checkbox" class="add-certificate-checkbox" 
    value="172">
    Collection Agency License
    </label>
  </li>
</ul>

我已经尝试了待办事项下方的两行 FindElement 并且都返回了 OpenQA.Selenium.NoSuchElementException:无法定位元素

new SelectElement(BaseTest.Driver.FindElement(By.Id("AddCertificateCountry")))
  .SelectByText("Canada");
new SelectElement(BaseTest.Driver.FindElement(By.Id("AddCertificateState")))
  .SelectByText("Alberta");

//TODO: correct input value for checkbox
new SelectElement(BaseTest.Driver.FindElement(By.CssSelector(
  "#CertificateToAdd>li:nth-child(2)"))).SelectByValue("172");

new SelectElement(BaseTest.Driver.FindElement(By.XPath(
  "//*[@id="CertificatesToAdd"]/li[2]/label/input"))).SelectByValue("172");

任何想法都会有所帮助和赞赏。

最佳答案

单击与 <label> 关联的复选框标签你可以使用以下解决方案:

  • 注册证书:

    BaseTest.Driver.FindElement(By.XPath("//label[@class='checkbox'][normalize-space()='Certificate of Registration']/input[@class='add-certificate-checkbox']")).Click();
    
  • 代收代理执照:

    BaseTest.Driver.FindElement(By.XPath("//label[@class='checkbox'][normalize-space()='Collection Agency License']/input[@class='add-certificate-checkbox']")).Click();
    

关于c# - Selenium/Chrome - 选择没有 ID 的复选框输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53527381/

相关文章:

c# - MediaElement 似乎在播放视频时禁用锁定屏幕

c# - 在 SSIS 脚本任务中为 C# 中的 for 循环转换字符串

python - Selenium 获取下一个 tr 给定条件适用于前一个 tr

c# - 您将 SQL 语句放在您的 C# 项目中的什么位置?

android - 配置错误 : Unable to run scripts on mobile Device

javascript - 为拖放的 selenium UI 集成测试执行 Javascript - Java

c# - 抛出异常 : 'OpenQA.Selenium.WebDriverException' in WebDriver. dll

selenium-webdriver - 机器人框架调用带有空格的 add_argument

java - 关于 Selenium 的新手问题

c# - 如何检查 GetStringAsync 是否导致 401(例如)?