java - How to return a lazily-instantiated dynamic webelement -
i've been using @findby
while now, , love fact element doesn't located until necessary (not on instantiation).
however, webpage may have anywhere 2-10 of element, , id's on elements numbered (so first element has id of "element1" , forth)
i write function can pass in integer, , return webelement appropriate id, and lazily instantiated. means having function following won't work:
public webelement getelement(int numonpage){ return driver.findelement(by.id("element"+numonpage)); }
because instant call function webelement gets located. (the reason why can't instantiated because have function waits until element exists calling isdisplayed() on , on over it, catching nosuchelementexception
s).
i realize create list<webelement>
selects via css every element id starts "element" have had other cases i've wanted return dynamically generated element, , had use workaround there well.
thanks!
first, don't understand why absolutely need webelement
reference before element in page. in normal case, check page loaded , find webelement
. first typically done loop , catch nosuchelementexception
mentioned.
however, if need reference webelement
before can't found in page, create proxy loads lazily (only when first time needed) real webelement
instance. this:
public webelement getelement(final int numonpage) { return (webelement) proxy.newproxyinstance(this.getclass().getclassloader(), new class<?>[] { webelement.class }, new invocationhandler() { // lazy initialized instance of webelement private webelement webelement; public object invoke(object proxy, method method, object[] args) throws throwable { if (webelement == null) { webelement = driver.findelement(by.id("element" + numonpage)); } return method.invoke(webelement, args); } }); }
by calling getelement
, retrieve object of type webelement
. call 1 of method, retrieved using webdriver.findelement
. note that, if call method on proxy instance, element must in page otherwise of course nosuchelementexception
.
Comments
Post a Comment