【问题标题】:Selenium: Element Not Found for existing elementSelenium:未找到现有元素的元素
【发布时间】:2020-10-21 03:13:27
【问题描述】:

所以我想用 Selenium 获取以下 HTML 标记:

<button data-v-48e2f75a="" class="app-button rose-button min-width">Sign in</button>

我正在尝试这样获取它:

...
browser.findElement(By.cssSelector("app-button rose-button min-width")).click();

当我运行它时,它总是返回以下异常:

org.openqa.selenium.NoSuchElementException: Unable to locate element: app-button rose-button min-width

这是我已经尝试过的方法之一,但它也没有奏效:

browser.findElement(By.cssSelector("app-button rose-button min-width")).click();

【问题讨论】:

    标签: java selenium selenium-webdriver


    【解决方案1】:

    要点击文本为 Sign in 的元素,您必须将 WebDriverWait 诱导为 elementToBeClickable(),并且您可以使用以下任一 Locator Strategies:

    • 使用cssSelector:

      new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("button.app-button.rose-button.min-width"))).click();
      
    • 使用xpath:

      new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@class='app-button rose-button min-width' and text()='Sign in']"))).click();
      

    参考

    您可以在以下位置找到一些详细的讨论:

    【讨论】:

      【解决方案2】:

      应该是 By.className 而不是 cssSelector。

      例子:

          WebElement parentElement = driver.findElement(By.className("rose-button"));
          
      

      如果你想使用 cssSelector,它应该是这样的:

      driver.findElement(By.cssSelector("button[class='app-button rose-button min-width']"));
      

      另一种方法是使用 xpath:

      driver.findElement(By.xpath("//div[@class='app-button rose-button min-width']"));
      

      正如 DebanjanB 所提到的,如果存在某种加载延迟,您也可以添加 webdriverwait。

      【讨论】:

      • 我不敢相信我犯了这样的错误哈哈,总是让我绊倒的小事。
      【解决方案3】:

      css 选择器错误。用这种方式试试:

      • browser.findElement(By.cssSelector(".app-button.rose-button.min-width")).click();

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-25
        • 2023-03-28
        • 2019-01-02
        • 2021-03-14
        相关资源
        最近更新 更多