不可靠的点击项Selenium WebdriverJS

Unreliable click item Selenium WebdriverJS

本文关键字:Selenium WebdriverJS 不可靠      更新时间:2023-09-26

我正在尝试从 React.js Web 应用程序中单击动态加载的项目。该项将打开一个模式窗口,类名为 newItemView 。我已经尝试了很多方法,但没有什么是可靠的。它会工作几次,但随后给我一个错误。

目标是单击动态项,然后单击模式窗口中的按钮。

尝试 1:

driver.wait(until.elementLocated(By.xpath(PATH_TO_DYNAMIC_ELEMENT)), MAX_WAIT_TIME,
      'Could not locate the element within the time specified')
      .then(function() {
          driver.findElement(By.xpath(PATH_TO_DYNAMIC_ELEMENT)).click();
      }); 
driver.wait(until.elementLocated(By.xpath(PATH_TO_MODAL_BUTTON)), MAX_WAIT_TIME,
      'Could not locate the modal element within the time specified')
      .then(function() {
          driver.findElement(By.xpath(PATH_TO_MODAL_BUTTON)).click();
      });

大约 5 次尝试中的一次,这会抛出'Could not locate the modal element within the time specified',因为模态实际上并没有打开。

尝试 2 等待,然后使用 Actions 移动到按钮上并单击:

driver.wait(until.elementLocated(By.xpath(PATH_TO_DYNAMIC_ELEMENT)), MAX_WAIT_TIME,
      'Could not locate the dynamic element within the time specified')
      .then(function() {
          driver.findElement(By.xpath(PATH_TO_DYNAMIC_ELEMENT))
                .then(function(PATH_TO_DYNAMIC_ELEMENT_BUTTON) {
                    var actions = new webdriver.ActionSequence(driver);
                    actions.mouseMove(PATH_TO_DYNAMIC_ELEMENT_BUTTON).click().perform();
                });
      });

然后执行检查以查看模式是否打开

driver.findElement(webdriver.By.className("newItemView"))
      .then(function() {
        driver.findElement(By.xpath(PATH_TO_MODAL_BUTTON)).click();
      }, function (err) {
          if (err.name === "NoSuchElementError")
              console.log("Element was missing!");
      });

这似乎效果更好,但仍然投掷了大约十分之一的次数。在网页上,Actions似乎有效,因为该项目在hover上显示,但它从未被点击过。

我认为你可以尝试使用JavaScript执行器...喜欢

WebElement YourElement= driver.findElement(By.id("YourElement-ID"));
JavascriptExecutor ExeCutor = (JavascriptExecutor)driver;
ExeCutor.executeScript("arguments[0].click();", YourElement);

你的第一个问题是你没有正确地链接你的承诺。 如果你扁平化你的承诺,就更容易看到问题:

return driver.wait(until.elementLocated(By.xpath(PATH_TO_DYNAMIC_ELEMENT)), MAX_WAIT_TIME,
  'Could not locate the dynamic element within the time specified')
  .then(function() {
      return driver.findElement(By.xpath(PATH_TO_DYNAMIC_ELEMENT));
  })
  .then(function(button) {
      var actions = new webdriver.ActionSequence(driver);
      return actions.mouseMove(button).click().perform();
  });

也就是说,在发送点击事件和浏览器做出反应之间仍然存在一些滞后。 例如,您可能需要添加等待新元素变得可见。