简体   繁体   English

selenium 根据索引位置获取 li 元素并单击复选框

[英]selenium get li element based on index position and click the checkbox

I have this HTML now using Selenium I ant to toggle the li element with given index position say 1, where it indicates I want to click the toggle checkbox for spring.我现在有这个 HTML 使用 Selenium 我蚂蚁切换给定索引位置的 li 元素,比如 1,它表示我想单击 spring 的切换复选框。

<ul id="todo-list" data-woven="abc">
<li class="active" data-index="0">
    <div class="view">
        <input class="toggle" type="checkbox">
        <label>Java</label>
        <button class="destroy"></button>
    </div>
    <input class="edit">
</li>
<li class="active" data-index="1">
    <div class="view">
        <input class="toggle" type="checkbox">
        <label>Spring</label>
        <button class="destroy"></button>
    </div>
    <input class="edit">
</li></ul>

I am completely new to selenium so not able to understand how can we achieve this.我对硒完全陌生,所以无法理解我们如何实现这一目标。

I know to get the UL elements using the code:我知道使用以下代码获取UL元素:

driver.findElement(By.id("todo-list"));

Now how can get the li element based on its index and click the corresponding checkbox .现在如何根据其index获取li元素并click相应的checkbox

To click on the checkbox element with respect to the ancestor <li> nodes index attribute you can use either of the following Locator Strategies :要单击与祖先<li>节点索引属性相关的复选框元素,您可以使用以下任一定位器策略

  • cssSelector : css选择器

     driver.findElement(By.cssSelector("ul#todo-list li.active[data-index='1'] input")).click();
  • xpath :路径

     driver.findElement(By.xpath("//ul[@id='todo-list']//li[@class='active' and @data-index='1']//input")).click();

You can use xpath to locate an element with data-index=1您可以使用xpath来定位data-index=1的元素

driver.findElement(By.xpath("//li[@data-index='1']//input[@class='toggle']"));

Or with cssSelector或者使用cssSelector

driver.findElement(By.cssSelector("[data-index='1'] .toggle"));

You could find the element you are looking for directly with the answer @Guy gave you and that would be the right way if you knew exactly what the data-index attribute would be set to, but you could also find a collection of the li elements and then proceed to do what you need within each like this:您可以通过@Guy 给您的答案直接找到您要查找的元素,如果您确切知道 data-index 属性将设置为什么,那将是正确的方法,但您也可以找到 li 元素的集合然后继续在每个中做你需要的事情:

var container = driver.findElement(By.id("todo-list"));

var elements = container.findElements(By.tagName("li"));

with elements you can loop through each or go directly to the one you want.使用元素,您可以遍历每个元素或直接转到您想要的元素。

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

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