单击具有role ='button'的div元素不起作用

时间:2019-11-20 12:41:57

标签: javascript selenium selenium-webdriver

单击具有role ='button'的div元素时无法操作。我需要单击该图标,但不能这样做。

html:

<div class="list">
  <div class="item">
    <div role="button" tabindex="-1">
      <strong>ItemName2</strong>
    </div>
    <div class="d">
      <div class="item-icon" role="button" tabindex="-1"  style="display: none">
        <i aria-label="icon: edit" class="edit"></i>
      </div>
    </div>
  </div>
  <div class="item"> ... </div>
  <div class="item"> ... </div>
  <div class="item"> ... </div>
</div>

js:

  try {
    await driver.get("http://127.0.0.1");

    let findButtons = await driver.findElements(By.tagName('strong'));

    let buttons = findButtons.map(elem => elem.getText());
    const allButtons = await Promise.all(buttons);
    console.log(allButtons);             // It is displayed all button values, such as ItemName1
    let tButton;
    for (let i = 0; i < findButtons.length; i++) {
      if (allButtons[i] == 'ItemName2') {
        tButton = await findButtons[i];
        tButton.click();                // I try to click on this button, where value = ItemName2
        console.log(allButtons[i]);     //  It is displayed button value 'ItemName2'    
      }}}

控制台错误:

(node:12254) UnhandledPromiseRejectionWarning: StaleElementReferenceError: stale element reference: element is not attached to the page document

2 个答案:

答案 0 :(得分:2)

您正在获取陈旧的元素异常,因为您尝试使用旧引用获取该元素。每次单击循环中的元素,元素引用都会更新,allButtons[i]不起作用。为了解决这个问题,您必须获取按钮的最新引用。请尝试以下。

js:

const { By, Key, until } = require("selenium-webdriver");
const webdriver = require("selenium-webdriver");
require("chromedriver");
async () => {
  let driver = await new webdriver.Builder().forBrowser("chrome").build();
  try {
    await driver.get("http://10.203.201.77:8000/login");

    let findButtons = await driver.findElements(By.tagName('strong'));

    let buttons = findButtons.map(elem => elem.getText());
    const allButtons = await Promise.all(buttons);
    console.log(allButtons);             // It is displayed all button values, such as ItemName1
    let tButton;
    for (let i = 0; i < findButtons.length; i++) {
      buttons = findButtons.map(elem => elem.getText()); # getting the button so that the elements refererence will refresh
      if (allButtons[i] == 'ItemName2') {
        tButton = await findButtons[i];
        tButton.click();                // I try to click on this button, where value = ItemName2
        console.log(allButtons[i]);     //  It is displayed button value 'ItemName2'

      }
    }
      console.log("DONE");
    } catch (e) {
      console.log(e);
    } finally {
      await driver.quit();
    }
  }
}

答案 1 :(得分:0)

我找到了解决方法:

 let findButtons = await driver.findElements(By.tagName('strong'));

 let buttons = findButtons.map(async elem => await elem.getText()); // I add async & await
 const allButtons = await Promise.all(buttons);
 console.log(allButtons);   // There are all itemName