【问题标题】:How to locate the element from the popup as per the HTML provided?如何根据提供的 HTML 从弹出窗口中定位元素?
【发布时间】:2018-07-19 06:53:43
【问题描述】:

这是我的 HTML 片段:

HTML:

<button class="confirm" tabindex="1" style="display: inline-block; background-color: rgb(140, 212, 245); box-shadow: rgba(140, 212, 245, 0.8) 0px 0px 2px, rgba(0, 0, 0, 0.05) 0px 0px 0px 1px inset;">OK</button>

我试图通过 Selenium WebDriver 单击确定按钮,但它给了我:错误:

no such element: Unable to locate element: {"method":"cssselector","selector":"button[class='confirm']"}

目前我在 Selenium 中使用此代码:

driver.findElement(By.cssSelector("button[class='confirm']"));

【问题讨论】:

  • 确保您的按钮不在某个 iframe 中。并尝试等待按钮可见。
  • 分享 button 的完整 HTML,并检查元素是否在任何 iframe 内

标签: java selenium selenium-webdriver xpath css-selectors


【解决方案1】:

根据您共享的 HTML,您需要诱导 WebDriverwait 以使所需的 元素可点击,您可以使用解决方案:

  • cssSelector:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("div.sa-confirm-button-container>button.confirm"))).click();
    
  • xpath:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@class='sa-confirm-button-container']/button[@class='confirm' and contains(.,'OK')]"))).click();
    

【讨论】:

  • @JaffarLone 如果这个/任何答案对您/对您有帮助,对未来的读者有帮助,请支持该答案。
【解决方案2】:

你可以试试这段代码:

//button[text()='OK' and @class='confirm']  

但是,请确保此按钮不应出现在任何iframe/frame/frameset 中。

如果是这种情况,那么您必须将 Web 驱动程序的焦点切换到所需/特定的 iframe/frame/frameset 才能与此按钮进行交互。

为此,您可以尝试以下代码:

 driver.switchTo().frame(arg0)  

请注意,arg0 可以是 frame numberframe nameframe as a web element

希望这会有所帮助。

【讨论】:

  • 试过这个代码 ==> driver.findElement(By.xpath("//*[@button[text()='OK'] and @class='confirm']"));仍然出现错误==>没有这样的元素:无法找到元素:{“method”:“xpath”,“selector”:“//* [@button[text()='OK']和@class='确认']"}
  • 那会发生什么?仍然没有这样的元素异常?如果是这种情况,那么我很确定其中涉及到 iframe。在开发工具中检查元素时,只需向上滚动并查看是否有任何 iframe 可用。
  • 请分享包含这个按钮的html和这个父级的父级,基本上我的目标是框架。用同样的方式更新我。
  • 此 HTML 在您之前与我们共享的图像中可用。请分享以上 HTML &lt;div class='sa-icon sa-error'&gt;
  • 猜你喜欢
    相关资源
    最近更新 更多
    热门标签