javascript - 对带有 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
解决方案
您正在获得陈旧的元素异常,因为您正在尝试使用旧引用获取元素。每次单击循环中的元素时,元素引用都会更新并且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();
}
}
}
推荐阅读
- angular - Angular 6 在两个不相关的组件之间传递数据
- vba - 具有计数功能并在单元格中搜索文本
- request - 如何在 EOS 中推送交易?
- php - OAuth2 , PHP 和 Quickbooks
- java - 骆驼缓存条目信息和配置
- html - 选择名称以 CSS 中特定字符串开头的所有元素
- ionic-framework - 错误:Angular AoT 构建失败。看上面的问题
- bazel - Bazel 通过一次调用构建多个目标架构?
- javascript - websocket.close() 函数继续运行后
- spring-integration - 在所有分区返回之前发生超时