无法在 Selenium 和 Java 中使用 className 定位元素

Unable to locate element using className in Selenium and Java

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

<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();

为什么有时能用有时不能用?

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

因为您能够找到以下元素:

<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 中还有其他元素以 className 呈现为 signup-button 甚至之前所需的元素,在设计上可能 不可见

理想情况下,您还应该能够使用 based :

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

最佳实践

但根据最佳实践,您需要使用 for the elementToBeClickable() and you can use either of the following :

  • 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();
    

参考资料

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