在Selenium和Java中无法使用className定位元素 [英] Unable to locate element using className in Selenium and Java

查看:510
本文介绍了在Selenium和Java中无法使用className定位元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I wanted to locate a element of a web page using class name in Selenium. This is the web element that I tried:

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

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

When I try this way, I was unable to locate the button;

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

但是,使用如下所示的css选择器,它正在工作;

But, using css selector like below, it was working;

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

有时工作而有时又不工作的原因是什么?

What is the reason for that sometimes working and other times not working?

推荐答案

您可以找到以下元素:

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

使用:

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

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

but was unable to locate the same element using:

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

那是因为在 HTML DOM 中还存在其他元素,这些元素带有 className 设为 signup-button ,甚至在所需元素之前,该元素在设计上可能不可见.

That's because there were other elements which renders within the HTML DOM with className as signup-button even before the desired element, which possibly may be invisible by design.

理想情况下,您还应该能够使用基于定位器策略:

Ideally, you should also be able to use a xpath based Locator Strategy:

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


最佳做法

但是,按照最佳做法,您需要使用定位器策略:


Best Practices

But as per best practices, you need to use WebDriverWait for the elementToBeClickable() and you can use either of the following 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();
    

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

    You can find a couple of relevant discussions in:

    这篇关于在Selenium和Java中无法使用className定位元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    相关文章
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆