我是Selenium
的新手,需要检查Selenium
Java
中的元素是否可点击,因为element.click()
在link
和label
都通过。
我尝试使用下面的代码,但没有工作:
WebDriverWait wait = new WebDriverWait(Scenario1Test.driver, 10);
if(wait.until(ExpectedConditions.elementToBeClickable(By.xpath("(//div[@id='brandSlider']/div[1]/div/div/div/img)[50]")))==null)
需要帮助。
elementToBeClickable
用于检查元素是否可见并启用,以便您可以单击它。
如果预期条件为真,ExpectedConditions.elementToBeClickable
返回WebElement
否则它将抛出TimeoutException
,它永远不会返回null
。
因此,如果你使用ExpectedConditions.elementToBeClickable
找到一个总会给你可点击元素的元素,所以不需要检查null
条件,你应该尝试如下: -
WebDriverWait wait = new WebDriverWait(Scenario1Test.driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("(//div[@id='brandSlider']/div[1]/div/div/div/img)[50]")));
element.click();
正如你所说element.click()
在link
和label
上传递的并不意味着元素不可点击,它意味着返回元素clicked
但可能没有事件在元素上执行单击操作。
注意: - 我建议你总是首先尝试通过id
,name
,className
和其他定位器找到元素。如果你遇到一些难以找到然后使用cssSelector
并始终给xpath
定位器的最后优先级,因为它比其他定位器找到一个元素慢。
希望它可以帮助你.. :)
有些情况下,element.isDisplayed() && element.isEnabled()
将返回true
但仍然元素将无法点击,因为它被其他元素隐藏/重叠。
在这种情况下,Exception
抓住的是:
org.openqa.selenium.WebDriverException:未知错误:元素在点(781,704)处无法点击。其他元素将收到点击:
<div class="footer">...</div>
请改用此代码:
WebElement element=driver.findElement(By.xpath"");
JavascriptExecutor ex=(JavascriptExecutor)driver;
ex.executeScript("arguments[0].click()", element);
它会工作。
wait.until(ExpectedConditions)
不会返回null,它将满足条件或抛出TimeoutException
。
您可以检查元素是否显示和启用
WebElement element = driver.findElement(By.xpath);
if (element.isDisplayed() && element.isEnabled()) {
element.click();
}
从源代码中你可以查看ExpectedConditions.elementToBeClickable()
,它将判断元素是否可见并启用,因此你可以将isEnabled()
与isDisplayed()
一起使用。以下是源代码。
public static ExpectedCondition<WebElement> elementToBeClickable(final WebElement element) {
return new ExpectedCondition() {
public WebElement apply(WebDriver driver) {
WebElement visibleElement = (WebElement) ExpectedConditions.visibilityOf(element).apply(driver);
try {
return visibleElement != null && visibleElement.isEnabled() ? visibleElement : null;
} catch (StaleElementReferenceException arg3) {
return null;
}
}
public String toString() {
return "element to be clickable: " + element;
}
};
}
begin
@locator.click
@locator.click
return true
rescue
return false
end