简体   繁体   中英

I have difficulty in deriving children from a Promise

There are list. I need to find Item 3 element and click on the '2' button in this element. What can I do it?

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
      }
    }

You can get element using xpath :

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

You can try following xpath :

//div[@class='item' and contains(.,'Item 3')]//button[2]

Or:

//p[contains(text(),'Item 3')]//parent::div//following-sibling::button[2]

button[2] - refers to the second button.

driver.findElement(By.xpath("//div//p[contains(.,'Item 3')]/parent::div/following-sibling::button[2]") 

hope this helps.

You can try following Xpath .

//div[@class='item'][.//p[normalize-space(.)='Item 3']]//button[2]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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