首页 > 解决方案 > 对带有 role='button' 的 div 元素的点击不起作用

问题描述

对带有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

标签: javascriptseleniumselenium-webdriver

解决方案


您正在获得陈旧的元素异常,因为您正在尝试使用旧引用获取元素。每次单击循环中的元素时,元素引用都会更新并且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();
    }
  }
}

推荐阅读