硒:检查元素的存在 [英] Selenium: Check for the presence of element
问题描述
在实时自动化中,我们是否在对每个元素(测试中)执行某些操作之前检查它们是否存在?
In real-time automation, do we check for the presence of every element(in test) before performing some action on them?
只要有 findElement
语句,就有可能出现 NoSuchElementException.我的问题是我们是否每次都检查元素的存在?
Wherever there is a findElement
statement, there is a chance of NoSuchElementException. My question is whether we check for the presence of the element everytime?
是否每个findElement
语句都需要被try-catch
块包围?
Does every findElement
statement need to be surrounded by try-catch
block?
推荐答案
你可能会发现 AbstractWebDriverEventListener 特别有用.该类实现接口 WebDriverEventListener 为 WebDriver 触发的事件定义了 before
和 after
钩子.
You may find the use of the class AbstractWebDriverEventListener particularly useful. This class implements the interface WebDriverEventListener which defines before
and after
hooks for the events triggered by WebDriver.
一个这样的前钩beforeFindBy 可以用来检查元素的存在.例如:
One such before hook beforeFindBy could be implemented to check the presence of element. For example:
public void beforeFindBy(By by, WebElement element, WebDriver driver) {
// Explicit wait to check for the presence of the element using the "by" locator
}
类似于 before 钩子 beforeClickOn 可以用来检查元素是否可点击,然后再对该元素执行点击事件.
Similarly the before hook beforeClickOn could be implemented to check that the element is clickable before the click event is performed on that element.
这篇关于硒:检查元素的存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!