在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: