Best Selenium code snippet using org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement
Source:SeleniumNativeActions.java
...67 currentFrame.put(uiDriver, frame);68 }69 70 /**71 * Intercept any call to driver.findElement(By.xx) made from a PageObject subclass and returns a HtmlElement instead of a RemoteWebElement72 * This way, every action done on this element will benefit from HtmlElement mechanism73 * @param joinPoint74 * @return75 * @throws Throwable76 */77 @Around("this(com.seleniumtests.uipage.PageObject) && call(public * org.openqa.selenium.WebDriver+.findElement (..))")78 public Object interceptFindHtmlElement(ProceedingJoinPoint joinPoint) throws Throwable {79 if (Boolean.TRUE.equals(doOverride())) {80 return new HtmlElement("", (By)(joinPoint.getArgs()[0]), getCurrentFrame());81 } else {82 return joinPoint.proceed(joinPoint.getArgs()); 83 }84 }85 86 @Around("this(com.seleniumtests.uipage.PageObject) && " + // caller is a PageObject87 "(call(public * org.openqa.selenium.WebDriver+.findElements (..))"88 + ")" 89 )90 public Object interceptFindsHtmlElement(ProceedingJoinPoint joinPoint) throws Throwable {91 if (Boolean.TRUE.equals(doOverride())) {92 return new HtmlElement("", (By)(joinPoint.getArgs()[0]), getCurrentFrame()).findElements();93 } else {94 return joinPoint.proceed(joinPoint.getArgs());95 }96 }97 98 /**99 * Intercept "findElement" action done in LocatingElementHandler class so that we can override returned element and replace it by HtmlElement100 * This helps handling PageObjectFactory method101 * @param joinPoint102 * @return103 * @throws Throwable104 */105 @Around(" this(org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler) && call(public * org.openqa.selenium.support.pagefactory.ElementLocator+.findElement (..))" 106 )107 public Object interceptPageFactoryElementLocation(ProceedingJoinPoint joinPoint) throws Throwable {108 if (Boolean.TRUE.equals(doOverride())) {109 DefaultElementLocator locator = ((DefaultElementLocator)joinPoint.getTarget());110 Field byField = DefaultElementLocator.class.getDeclaredField("by");111 byField.setAccessible(true);112 return new HtmlElement("", (By)byField.get(locator), getCurrentFrame());113 } else {114 return joinPoint.proceed(joinPoint.getArgs()); 115 }116 }117 118 /**119 * Intercept "findElements" action done in LocatingElementListHandler class so that we can override returned element and replace it by HtmlElement120 * This helps handling PageObjectFactory method121 * @param joinPoint122 * @return123 * @throws Throwable124 */125 @Around(" this(org.openqa.selenium.support.pagefactory.internal.LocatingElementListHandler) && call(public * org.openqa.selenium.support.pagefactory.ElementLocator+.findElements (..))" 126 )127 public Object interceptPageFactoryElementsLocation(ProceedingJoinPoint joinPoint) throws Throwable {128 if (doOverride()) {129 DefaultElementLocator locator = ((DefaultElementLocator)joinPoint.getTarget());130 Field byField = DefaultElementLocator.class.getDeclaredField("by");131 byField.setAccessible(true);132 return new HtmlElement("", (By)byField.get(locator), getCurrentFrame()).findElements();133 } else {134 return joinPoint.proceed(joinPoint.getArgs()); 135 }136 }137 138 /**139 * Method interceptFindHtmlElement creates an HtmlElement from findElement, but does not handle frames. 140 * Here, we record all switchTo().frame(WebElement) call to create a FrameElement chain141 * @param joinPoint142 * @return143 * @throws Throwable144 */145 @Around("this(com.seleniumtests.uipage.PageObject) && " + // caller is a PageObject146 "(call(public * org.openqa.selenium.support.ui.ExpectedConditions.frameToBeAvailableAndSwitchToIt (..))"147 + ")" 148 )149 public Object recordFrameSwitch(ProceedingJoinPoint joinPoint) throws Throwable {150 if (Boolean.TRUE.equals(doOverride())) {151 Object frameArg = joinPoint.getArgs()[0];152 FrameElement frameEl = getFrameElement(frameArg);153 154 if (frameEl == null) {155 return joinPoint.proceed(joinPoint.getArgs());156 }157 158 if (getCurrentFrame() == null) {159 setCurrentFrame(frameEl);160 } else {161 frameEl.setFrameElement(getCurrentFrame());162 setCurrentFrame(frameEl);163 }164165 return new ExpectedCondition<WebDriver>() {166 @Override167 public WebDriver apply(WebDriver driver) {168 try {169 return driver;170 } catch (NoSuchFrameException e) {171 return null;172 }173 }174175 @Override176 public String toString() {177 return "frame to be available: " + frameArg;178 }179 };180 181 } else {182 return joinPoint.proceed(joinPoint.getArgs());183 }184 }185 186 /**187 * Method interceptFindHtmlElement creates an HtmlElement from findElement, but does not handle frames. 188 * Here, we record all switchTo().frame(WebElement) call to create a FrameElement chain189 * @param joinPoint190 * @return191 * @throws Throwable192 */193 @Around("this(com.seleniumtests.uipage.PageObject) && " + // caller is a PageObject194 "(call(public * org.openqa.selenium.WebDriver.TargetLocator+.frame (..))"195 + ")" 196 )197 public Object recordSwitchToFramCalls(ProceedingJoinPoint joinPoint) throws Throwable {198 if (Boolean.TRUE.equals(doOverride())) {199 Object frameArg = joinPoint.getArgs()[0];200 FrameElement frameEl = getFrameElement(frameArg);201 202 if (frameEl == null) {203 return joinPoint.proceed(joinPoint.getArgs());204 }205206 if (getCurrentFrame() == null) {207 setCurrentFrame(frameEl);208 } else {209 frameEl.setFrameElement(getCurrentFrame());210 setCurrentFrame(frameEl);211 }212 return null;213 } else {214 return joinPoint.proceed(joinPoint.getArgs());215 }216 }217 218 /**219 * Returns a FrameElement based on the object passed in argument220 * @param frameArg221 * @return222 * @throws SecurityException 223 * @throws NoSuchFieldException 224 * @throws IllegalAccessException 225 * @throws IllegalArgumentException 226 */227 private FrameElement getFrameElement(Object frameArg) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {228 FrameElement frameEl = null;229 230 if (frameArg instanceof HtmlElement) {231 frameEl = new FrameElement("", ((HtmlElement)frameArg).getBy());232 } else if (frameArg instanceof WebElement && frameArg.getClass().getName().contains("Proxy")) {233 LocatingElementHandler locatingEh = (LocatingElementHandler)Proxy.getInvocationHandler(frameArg);234 Field locatorField = LocatingElementHandler.class.getDeclaredField("locator");235 locatorField.setAccessible(true);236 DefaultElementLocator locator = ((DefaultElementLocator)locatorField.get(locatingEh));237 Field byField = DefaultElementLocator.class.getDeclaredField("by");238 byField.setAccessible(true);239 frameEl = new FrameElement("", (By)byField.get(locator));240 } else if (frameArg instanceof By) {241 frameEl = new FrameElement("", (By)frameArg);242 } else if (frameArg instanceof Integer) {243 frameEl = new FrameElement("", By.tagName("iframe"), (Integer) frameArg);244 } else if (frameArg instanceof String) {245 String name = ((String)frameArg).replaceAll("(['\"\\\\#.:;,!?+<>=~*^$|%&@`{}\\-/\\[\\]\\(\\)])", "\\\\$1");246 frameEl = new FrameElement("", By.cssSelector("frame[name='" + name + "'],iframe[name='" + name + "'],frame#" + name + ",iframe#" + name));247 }248 return frameEl;249 }250 251 @Around("this(com.seleniumtests.uipage.PageObject) && " + // caller is a PageObject252 "(call(public * org.openqa.selenium.WebDriver.TargetLocator+.defaultContent (..))"253 + ")" 254 )255 public Object recordSwitchDefaultContext(ProceedingJoinPoint joinPoint) throws Throwable {256 setCurrentFrame(null);257 return joinPoint.proceed(joinPoint.getArgs());258 }259 260 261 @Around("this(com.seleniumtests.uipage.PageObject) && " + // caller is a PageObject262 "(call(public * org.openqa.selenium.WebDriver.TargetLocator+.parentFrame (..))"263 + ")" 264 )265 public Object recordSwitchParentFrame(ProceedingJoinPoint joinPoint) throws Throwable {266 FrameElement curFrame = getCurrentFrame();267 if (curFrame == null || !doOverride()) {268 return joinPoint.proceed(joinPoint.getArgs());269 } else {270 setCurrentFrame(curFrame.getFrameElement());271 }272 return null;273 274 }275 276 277 278 // TODO: handle findElementBy... (from RemoteWebDriver) => should be useless as SeleniuRobot only expose a WebDriverInstance279 // TODO: check behavior with WebDriverWait & CompositeActions280}
...
Source:ScopedElementLocator.java
...50 * Constructs a scope out of the scope factory and the parent field, then searches for the injected field51 * in this scope.52 */53 @Override54 public WebElement findElement() {55 WebElement context = scopeFactory.createLocator(scopeField).findElement();56 return new DefaultElementLocator(context, searchField).findElement();57 }58 /**59 * Constructs a scope out of the scope factory and the parent field, then searches for the injected field60 * in this scope.61 */62 @Override63 public List<WebElement> findElements() {64 return scopeFactory.createLocator(scopeField).findElements().stream()65 .flatMap(element -> new DefaultElementLocator(element, searchField).findElements().stream())66 .collect(toList());67 }68}
Source:SelectorScopedElementLocator.java
...51 this.selector = selector;52 this.field = field;53 }54 @Override55 public WebElement findElement() {56 SearchContext context = getContext();57 return new DefaultElementLocator(context, field).findElement();58 }59 @Override60 public List<WebElement> findElements() {61 return selector.findElements(searchContext).stream()62 .flatMap(webElement -> new DefaultElementLocator(webElement, field).findElements().stream())63 .collect(toList());64 }65 private SearchContext getContext() {66 return field.isAnnotationPresent(Global.class) ? searchContext67 : selector.findElement(searchContext);68 }69}
Source:PageObjectFactory.java
...19 result.setRootElementSupplier(rootSearchContextSupplier);20 // lookup the root context whenever the search context is requested21 SearchContext searchContext = new SearchContext() {22 @Override23 public List<WebElement> findElements(By by) {24 return rootSearchContextSupplier.get().findElements(by);25 }26 @Override27 public WebElement findElement(By by) {28 return rootSearchContextSupplier.get().findElement(by);29 }30 };31 PageFactory.initElements(new ElementLocatorFactory() {32 @Override33 public ElementLocator createLocator(Field field) {34 try {35 field.setAccessible(true);36 if (field.get(result) != null)37 return null;38 else39 return new DefaultElementLocator(searchContext, field);40 } catch (Exception e) {41 throw new RuntimeException("Error while determining if page object field is already set", e);42 }...
Source:DefaultElementLocator.java
...23 }24 /**25 * Find the element.26 */27 public WebElement findElement() {28 if (cachedElement != null && shouldCache()) {29 return cachedElement;30 }31 WebElement element = provider.getDriver().findElement(by);32 if (shouldCache()) {33 cachedElement = element;34 }35 return element;36 }37 /**38 * Find the element list.39 */40 public List<WebElement> findElements() {41 if (cachedElementList != null && shouldCache()) {42 return cachedElementList;43 }44 List<WebElement> elements = provider.getDriver().findElements(by);45 if (shouldCache()) {46 cachedElementList = elements;47 }48 return elements;49 }50 /**51 * Returns whether the element should be cached.52 *53 * @return {@code true} if the element should be cached54 */55 protected boolean shouldCache() {56 return shouldCache;57 }58 @Override...
Source:JPageFactoryElementLocator.java
...18 AbstractAnnotations annotations) {19 super(searchContext, annotations);20 }21 @Override22 public WebElement findElement() {23 WebElement element = super.findElement();24 return (element instanceof NgWebElement)25 ? ((NgWebElement) element).getWrappedElement() : element;26 }27 @Override28 public List<WebElement> findElements() {29 List<WebElement> elements = super.findElements();30 for (int i = 0; i < elements.size(); i++) {31 WebElement element = elements.get(i);32 if (element instanceof NgWebElement) {33 elements.add(i, ((NgWebElement) element).getWrappedElement());34 }35 }36 return elements;37 }38}...
Source:PageElementLocator.java
...12 super(searchContext, annotations);13 this.searchContext = searchContext;14 }15 @Override16 public PageElement findElement() {17 WebElement element = super.findElement();18 return new AbstractPageElement(element, ((WebDriver) searchContext));19 }20 @Override21 public List<WebElement> findElements() {22 return super.findElements();23 }24}...
Source:MyElementLocator.java
...7 public MyElementLocator(SearchContext searchContext, AbstractAnnotations annotationsHandler) {8 super(searchContext, annotationsHandler);9 }10 @Override11 public WebElement findElement() {12 throw new MyException("I'll never find any elements for you!");13 }14 public class MyException extends RuntimeException {15 public MyException(String string) {16 super(string);17 }18 }19}...
findElement
Using AI Code Generation
1public class DefaultElementLocator implements ElementLocator {2 private final SearchContext searchContext;3 private final boolean shouldCache;4 private final By by;5 private WebElement cachedElement;6 private List<WebElement> cachedElementList;7 public DefaultElementLocator(SearchContext searchContext, Field field) {8 this(searchContext, new Annotations(field));9 }10 public DefaultElementLocator(SearchContext searchContext, Annotations annotations) {11 this.searchContext = searchContext;12 this.shouldCache = annotations.isLookupCached();13 this.by = annotations.buildBy();14 }15 public WebElement findElement() {16 if (cachedElement != null && shouldCache) {17 return cachedElement;18 }19 WebElement element = searchContext.findElement(by);20 if (shouldCache) {21 cachedElement = element;22 }23 return element;24 }25 public List<WebElement> findElements() {26 if (cachedElementList != null && shouldCache) {27 return cachedElementList;28 }29 List<WebElement> elements = searchContext.findElements(by);30 if (shouldCache) {31 cachedElementList = elements;32 }33 return elements;34 }35}36public class DefaultElementLocator implements ElementLocator {37 private final SearchContext searchContext;38 private final boolean shouldCache;39 private final By by;40 private WebElement cachedElement;41 private List<WebElement> cachedElementList;42 public DefaultElementLocator(SearchContext searchContext, Field field) {43 this(searchContext, new Annotations(field));44 }45 public DefaultElementLocator(SearchContext searchContext, Annotations annotations) {46 this.searchContext = searchContext;47 this.shouldCache = annotations.isLookupCached();48 this.by = annotations.buildBy();49 }50 public WebElement findElement() {51 if (cachedElement != null && shouldCache) {52 return cachedElement;53 }54 WebElement element = searchContext.findElement(by);55 if (shouldCache) {56 cachedElement = element;57 }58 return element;59 }60 public List<WebElement> findElements() {61 if (cachedElementList != null && shouldCache) {62 return cachedElementList;63 }64 List<WebElement> elements = searchContext.findElements(by);65 if (shouldCache) {
findElement
Using AI Code Generation
1package pagefactory;2import org.openqa.selenium.SearchContext;3import org.openqa.selenium.WebElement;4import org.openqa.selenium.support.pagefactory.DefaultElementLocator;5import org.openqa.selenium.support.pagefactory.DefaultElementLocatorFactory;6import org.openqa.selenium.support.pagefactory.ElementLocator;7import org.openqa.selenium.support.pagefactory.ElementLocatorFactory;8public class FindElementDemo {9 public static void main(String[] args) {10 ElementLocatorFactory elementLocatorFactory = new DefaultElementLocatorFactory(null);11 ElementLocator locator = elementLocatorFactory.createLocator(null);12 WebElement element = locator.findElement();13 DefaultElementLocator defaultElementLocator = new DefaultElementLocator((SearchContext) null, null);14 WebElement element1 = defaultElementLocator.findElement();15 }16}17 at pagefactory.FindElementDemo.main(FindElementDemo.java:25)
findElement
Using AI Code Generation
1public class DefaultElementLocator implements ElementLocator {2 private final SearchContext searchContext;3 private final boolean shouldCache;4 private final By by;5 private List<WebElement> cachedElement;6 public DefaultElementLocator(SearchContext searchContext, Field field) {7 this(searchContext, new Annotations(field));8 }9 public DefaultElementLocator(SearchContext searchContext, Annotations annotations) {10 this.searchContext = searchContext;11 this.shouldCache = annotations.isLookupCached();12 this.by = annotations.buildBy();13 }14 public WebElement findElement() {15 if (cachedElement != null && shouldCache) {16 return cachedElement.get(0);17 }18 WebElement element = searchContext.findElement(by);19 if (shouldCache) {20 cachedElement = Collections.singletonList(element);21 }22 return element;23 }24 public List<WebElement> findElements() {25 if (cachedElement != null && shouldCache) {26 return cachedElement;27 }28 List<WebElement> elements = searchContext.findElements(by);29 if (shouldCache) {30 cachedElement = elements;31 }32 return elements;33 }34}
findElement
Using AI Code Generation
1public class DefaultElementLocator implements ElementLocator {2 private final SearchContext searchContext;3 private final boolean shouldCache;4 private final By by;5 private WebElement cachedElement;6 private List<WebElement> cachedElementList;7 public DefaultElementLocator(SearchContext searchContext, Field field) {8 this(searchContext, new Annotations(field));9 }10 public DefaultElementLocator(SearchContext searchContext, Annotations annotations) {11 this.searchContext = searchContext;12 this.shouldCache = annotations.isLookupCached();13 this.by = annotations.buildBy();14 }15 public WebElement findElement() {16 if (cachedElement != null && shouldCache) {17 return cachedElement;18 }19 WebElement element = searchContext.findElement(by);20 if (shouldCache) {21 cachedElement = element;22 }23 return element;24 }25 public List<WebElement> findElements() {26 if (cachedElementList != null && shouldCache) {27 return cachedElementList;28 }29 List<WebElement> elements = searchContext.findElements(by);30 if (shouldCache) {31 cachedElementList = elements;32 }33 return elements;34 }35}36public class DefaultElementLocatorFactory implements ElementLocatorFactory {37 private final SearchContext searchContext;38 public DefaultElementLocatorFactory(SearchContext searchContext) {39 this.searchContext = searchContext;40 }41 public ElementLocator createLocator(Field field) {42 return new DefaultElementLocator(searchContext, field);43 }44}45public class LocatingElementHandler implements InvocationHandler {46 private final ElementLocator locator;47 private final boolean isText;48 public LocatingElementHandler(ElementLocator locator, boolean isText) {49 this.locator = locator;50 this.isText = isText;51 }52 public Object invoke(Object object, Method method, Object[] objects) throws Throwable {53 WebElement element = locator.findElement();54 if ("toString".equals(method.getName())) {55 return "Proxy element for: " + element;56 }
LambdaTest’s Selenium 4 tutorial is covering every aspects of Selenium 4 testing with examples and best practices. Here you will learn basics, such as how to upgrade from Selenium 3 to Selenium 4, to some advanced concepts, such as Relative locators and Selenium Grid 4 for Distributed testing. Also will learn new features of Selenium 4, such as capturing screenshots of specific elements, opening a new tab or window on the browser, and new protocol adoptions.
Upgrading From Selenium 3 To Selenium 4?: In this chapter, learn in detail how to update Selenium 3 to Selenium 4 for Java binding. Also, learn how to upgrade while using different build tools such as Maven or Gradle and get comprehensive guidance for upgrading Selenium.
What’s New In Selenium 4 & What’s Being Deprecated? : Get all information about new implementations in Selenium 4, such as W3S protocol adaption, Optimized Selenium Grid, and Enhanced Selenium IDE. Also, learn what is deprecated for Selenium 4, such as DesiredCapabilites and FindsBy methods, etc.
Selenium 4 With Python: Selenium supports all major languages, such as Python, C#, Ruby, and JavaScript. In this chapter, learn how to install Selenium 4 for Python and the features of Python in Selenium 4, such as Relative locators, Browser manipulation, and Chrom DevTool protocol.
Selenium 4 Is Now W3C Compliant: JSON Wireframe protocol is retiring from Selenium 4, and they are adopting W3C protocol to learn in detail about the advantages and impact of these changes.
How To Use Selenium 4 Relative Locator? : Selenium 4 came with new features such as Relative Locators that allow constructing locators with reference and easily located constructors nearby. Get to know its different use cases with examples.
Selenium Grid 4 Tutorial For Distributed Testing: Selenium Grid 4 allows you to perform tests over different browsers, OS, and device combinations. It also enables parallel execution browser testing, reads up on various features of Selenium Grid 4 and how to download it, and runs a test on Selenium Grid 4 with best practices.
Selenium Video Tutorials: Binge on video tutorials on Selenium by industry experts to get step-by-step direction from automating basic to complex test scenarios with Selenium.
LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.
Get 100 minutes of automation test minutes FREE!!