有清单。我需要找到Item 3元素,然后单击此元素中的“ 2”按钮。我该怎么办?

的HTML:

<body>
  <div class="list>
    <div class="item">
      <div>
       <p> Item 1 </p>
      </div>
      <button class='btn'> 1 </button>
      <button class='btn'> 2 </button>
    </div>
    <div class="item">
      <div>
       <p> Item 2 </p>
      </div>
      <button class='btn'> 1 </button>
      <button class='btn'> 2 </button>
    </div>
    <div class="item">
      <div>
       <p> Item 3 </p>
      </div>
      <button class='btn'> 1 </button>
      <button class='btn'> 2 </button>
    </div>
    <div class="item">
      <div>
       <p> Item 4 </p>
      </div>
      <button class='btn'> 1 </button>
      <button class='btn'> 2 </button>
    </div>
  </div>
</body>


js:

let findButtons = await
    driver.findElements(By.className('item'));

    let buttons = findButtons.map(elem => elem.getText());
    const allButtons = await Promise.all(buttons);

    //    ***   Find button  ***
    let tButton;
    for (let i = 0; i < findButtons.length; i++) {
      if (allButtons[i] == `Item 3`) {   // compare all elements. Find `Item 3` element
        tButton = await findButtons[i];
        console.log(tButton.children);   // need to display list of the children elements,
  but it is displayed - underfined

             tButton.click();                 // click on the element is available
        // but I need to click on the '2' button in the `Item 3` element
      }
    }

最佳答案

您可以使用xpath获得元素:

driver.findElement(By.xpath("//div[@class='item' and contains(.,'Item 2')]//button[normalize-space(.)='2']")).click();

关于javascript - 我很难从 promise 中派生 child ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58929681/

10-09 15:26