检查Selenium Java中是否可以单击元素
我是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
用于检查元素是否可见并启用,以便您可以单击它。
如果期望条件为true,则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
上传递,这并不意味着元素不可点击,这意味着点击了返回的元素,但可能没有事件在逐个元素上执行。
注意 : – 我建议你总是先尝试按id
, name
, className
和其他定位器查找元素。 如果你遇到一些难以找到然后使用cssSelector
并始终给xpath
定位器的最后优先级,因为它比其他定位器更慢地定位元素。
希望它可以帮助你.. 🙂
有些情况下, element.isDisplayed() && element.isEnabled()
将返回true
但仍然无法点击元素,因为它被其他元素隐藏/重叠。 在这种情况下,捕获的Exception
是:
org.openqa.selenium.WebDriverException:未知错误:元素在点(781,704)处无法点击。 其他元素将收到点击:… USE >>>>>>>
WebElement element=driver.findElement(By.xpath""); JavascriptExecutor ex=(JavascriptExecutor)driver; ex.executeScript("arguments[0].click()", element);
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 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