【问题标题】:Unable to locate element using className in Selenium and Java无法在 Selenium 和 Java 中使用 className 定位元素
【发布时间】:2020-11-06 21:59:33
【问题描述】:

我想在 Selenium 中使用类名来定位网页的元素。这是我尝试过的网络元素:

<button class="signup-button b green">Get Started!</button>

当我尝试这种方式时,我无法找到按钮;

driver.findElement(By.className("signup-button")).click();

但是,使用下面的 css 选择器,它可以工作;

driver.findElement(By.cssSelector("button.signup-button")).click();

为什么有时能工作有时不能工作?

【问题讨论】:

  • 请先检查您的页面没有 iFrame 元素。如果有,你应该在'findEelement'之前切换到所需的帧

标签: java selenium xpath css-selectors webdriverwait


【解决方案1】:

您可以找到以下元素:

<button class="signup-button b green">Get Started!</button>

使用:

driver.findElement(By.cssSelector("button.signup-button")).click();

但无法使用以下方法找到相同的元素:

driver.findElement(By.className("signup-button")).click();

这是因为在 HTML DOM 中还有其他元素呈现在 classNamesignup-button 甚至在所需元素之前,这可能是不可见的 设计。

理想情况下,您还应该能够使用基于Locator Strategy

driver.findElement(By.xpath("//button[@class='signup-button' and text()='Get Started!']")).click();

最佳实践

但根据最佳实践,您需要将WebDriverWait 用于elementToBeClickable(),并且您可以使用以下任一Locator Strategies

  • cssSelector:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("button.signup-button"))).click();
    
  • xpath:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@class='signup-button' and text()='Get Started!']"))).click();
    

参考文献

您可以在以下位置找到一些相关讨论:

【讨论】:

  • 感谢您的回答。我很满意。
【解决方案2】:

如果你没有像 id 和 class name 这样的定位器,你需要使用相对 xpath 你可以试试 //button[contains(text(),"Get Started!")] 这个 xpath

【讨论】:

    猜你喜欢
    • 2020-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多