Javascript 通过 Id 和 Xpath 执行点击的代码执行得如此之快

Javascript code to do clicks by Id and by Xpath executes so fast

我对 Javascript 很陌生。我尝试使用 "execute Script" 命令在 Selenium IDE 中设置一个 javascript 代码,以便打开共享相同 class="MyClass" 的设置按钮(有16 个按钮)。

点击按钮后会出现一个带有一些选项的 window。当这些选项可见时,我想单击 Xpath 可以定位的选项, 最后我想保存每个按钮的设置,然后对 16 个按钮重复相同的设置。

到目前为止,我的代码似乎部分有效,因为找到了 16 按钮,我可以执行 for 循环并单击它们,但运行速度似乎如此之快 这会导致其他操作未完成。

var items = document.getElementsByClassName("MyClass"); 
for (var i = 0; i < items.length; i++) {
    items[i].click(); // To open each button that have the class = "MyClass"
    document.evaluate(" //li[contains(.,'sometext')] ", document.body, null, 9, null). singleNodeValue.click(); // Click on elemenet by Xpath
    document.getElementById("savesettings").click(); // Save settings
};

我怎样才能像这样添加一些停顿?

var items = document.getElementsByClassName("MyClass"); 
for (var i = 0; i < items.length; i++) {
    items[i].click(); // To open each button that have the class = "MyClass"

    **Command to wait 2 seconds**

    document.evaluate(" //li[contains(.,'sometext')] ", document.body, null, 9, null). singleNodeValue.click(); // Click on elemenet by Xpath

    **Command to wait 2 seconds**

    document.getElementById("savesettings").click(); 
};

在此先感谢您的帮助。

我不太确定你在这里要做什么,但你可以使用 window.setTimeout 函数延迟执行。这将在 pre-determined 时间后触发一个函数。

在此函数中,您可以决定要做什么 - 启动另一个超时或执行某些操作 right-away - 使用简单的 switch-block.

var items = document.getElementsByClassName("MyClass");
var currentItem = 0;
var currentAction = 0;

function update() {
  switch (currentAction) {
    case 0:
      items[currentItem].click();
      currentAction = 1;
      window.setTimeout(update, 2000);
      break;
    case 1:
      document.evaluate(" //li[contains(.,'sometext')] ", document.body, null, 9, null).singleNodeValue.click(); // Click on elemenet by Xpath
      currentAction = 2;
      window.setTimeout(update, 2000);
      break;
    case 2:
      document.getElementById("savesettings").click();
      currentAction = 0;
      if (currentItem + 1 < items.length) {
        currentItem++;
        update();
      }
      break;
  }
}

update();

看起来你应该使用 Promises:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

这里有答案:

你可以在那里拿这个例子并在你的代码中实现它:

for (let i = 0, p = Promise.resolve(); i < 10; i++) {
    p = p.then(_ => new Promise(resolve =>
        setTimeout(function () {
            console.log(i);
            resolve();
        }, Math.random() * 1000)
    ));
}