检查Selenium Java中是否可以单击元素

问题描述 投票:8回答:5

我是Selenium的新手,需要检查Selenium Java中的元素是否可点击,因为element.click()linklabel都通过。

我尝试使用下面的代码,但没有工作:

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)

需要帮助。

java selenium selenium-webdriver automation
5个回答
12
投票

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()linklabel上传递的并不意味着元素不可点击,它意味着返回元素clicked但可能没有事件在元素上执行单击操作。

注意: - 我建议你总是首先尝试通过idnameclassName和其他定位器找到元素。如果你遇到一些难以找到然后使用cssSelector并始终给xpath定位器的最后优先级,因为它比其他定位器找到一个元素慢。

希望它可以帮助你.. :)


10
投票

有些情况下,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);

它会工作。


4
投票

wait.until(ExpectedConditions)不会返回null,它将满足条件或抛出TimeoutException

您可以检查元素是否显示和启用

WebElement element = driver.findElement(By.xpath);
if (element.isDisplayed() && element.isEnabled()) {
    element.click();
}

0
投票

从源代码中你可以查看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;
			}
		};
	}

-3
投票
 begin
      @locator.click
      @locator.click
      return true
rescue
      return false
end
© www.soinside.com 2019 - 2024. All rights reserved.