Best Selenium code snippet using org.openqa.selenium.By.Remotable.Parameters
Source:RemoteWebDriver.java
...387 return element;388 }389 RemoteWebElement remoteElement = (RemoteWebElement) element;390 if (locator instanceof By.Remotable) {391 By.Remotable.Parameters params = ((By.Remotable) locator).getRemoteParameters();392 remoteElement.setFoundBy(context, params.using(), String.valueOf(params.value()));393 }394 remoteElement.setFileDetector(parent.getFileDetector());395 remoteElement.setParent(parent);396 return remoteElement;397 }398 /**399 * @deprecated Rely on using {@link By.Remotable} instead400 */401 @Deprecated402 protected WebElement findElement(String by, String using) {403 throw new UnsupportedOperationException("`findElement` has been replaced by usages of " + By.Remotable.class);404 }405 /**406 * @deprecated Rely on using {@link By.Remotable} instead407 */408 @Deprecated409 protected List<WebElement> findElements(String by, String using) {410 throw new UnsupportedOperationException("`findElement` has been replaced by usages of " + By.Remotable.class);411 }412 protected void setFoundBy(SearchContext context, WebElement element, String by, String using) {413 if (element instanceof RemoteWebElement) {414 RemoteWebElement remoteElement = (RemoteWebElement) element;415 remoteElement.setFoundBy(context, by, using);416 remoteElement.setFileDetector(getFileDetector());417 }418 }419 // Misc420 @Override421 public String getPageSource() {422 return (String) execute(DriverCommand.GET_PAGE_SOURCE).getValue();423 }424 @Override425 public void close() {426 execute(DriverCommand.CLOSE);427 }428 @Override429 public void quit() {430 // no-op if session id is null. We're only going to make ourselves unhappy431 if (sessionId == null) {432 return;433 }434 try {435 execute(DriverCommand.QUIT);436 } finally {437 sessionId = null;438 }439 }440 @Override441 @SuppressWarnings({"unchecked"})442 public Set<String> getWindowHandles() {443 Response response = execute(DriverCommand.GET_WINDOW_HANDLES);444 Object value = response.getValue();445 try {446 List<String> returnedValues = (List<String>) value;447 return new LinkedHashSet<>(returnedValues);448 } catch (ClassCastException ex) {449 throw new WebDriverException(450 "Returned value cannot be converted to List<String>: " + value, ex);451 }452 }453 @Override454 public String getWindowHandle() {455 return String.valueOf(execute(DriverCommand.GET_CURRENT_WINDOW_HANDLE).getValue());456 }457 @Override458 public Object executeScript(String script, Object... args) {459 if (!isJavascriptEnabled()) {460 throw new UnsupportedOperationException(461 "You must be using an underlying instance of WebDriver that supports executing javascript");462 }463 // Escape the quote marks464 script = script.replaceAll("\"", "\\\"");465 List<Object> convertedArgs = Stream.of(args).map(new WebElementToJsonConverter()).collect(466 Collectors.toList());467 return execute(DriverCommand.EXECUTE_SCRIPT(script, convertedArgs)).getValue();468 }469 @Override470 public Object executeAsyncScript(String script, Object... args) {471 if (!isJavascriptEnabled()) {472 throw new UnsupportedOperationException("You must be using an underlying instance of " +473 "WebDriver that supports executing javascript");474 }475 // Escape the quote marks476 script = script.replaceAll("\"", "\\\"");477 List<Object> convertedArgs = Stream.of(args).map(new WebElementToJsonConverter()).collect(478 Collectors.toList());479 return execute(DriverCommand.EXECUTE_ASYNC_SCRIPT(script, convertedArgs)).getValue();480 }481 private boolean isJavascriptEnabled() {482 return getCapabilities().is(SUPPORTS_JAVASCRIPT);483 }484 @Override485 public TargetLocator switchTo() {486 return new RemoteTargetLocator();487 }488 @Override489 public Navigation navigate() {490 return new RemoteNavigation();491 }492 @Override493 public Options manage() {494 return new RemoteWebDriverOptions();495 }496 protected void setElementConverter(JsonToWebElementConverter converter) {497 this.converter = Require.nonNull("Element converter", converter);498 }499 protected JsonToWebElementConverter getElementConverter() {500 return converter;501 }502 /**503 * Sets the RemoteWebDriver's client log level.504 *505 * @param level The log level to use.506 */507 public void setLogLevel(Level level) {508 this.level = level;509 logger.setLevel(level);510 }511 protected Response execute(CommandPayload payload) {512 Command command = new Command(sessionId, payload);513 Response response;514 long start = System.currentTimeMillis();515 String currentName = Thread.currentThread().getName();516 Thread.currentThread().setName(517 String.format("Forwarding %s on session %s to remote", command.getName(), sessionId));518 try {519 log(sessionId, command.getName(), command, When.BEFORE);520 response = executor.execute(command);521 log(sessionId, command.getName(), response, When.AFTER);522 if (response == null) {523 return null;524 }525 // Unwrap the response value by converting any JSON objects of the form526 // {"ELEMENT": id} to RemoteWebElements.527 Object value = getElementConverter().apply(response.getValue());528 response.setValue(value);529 } catch (Throwable e) {530 log(sessionId, command.getName(), command, When.EXCEPTION);531 WebDriverException toThrow;532 if (command.getName().equals(DriverCommand.NEW_SESSION)) {533 if (e instanceof SessionNotCreatedException) {534 toThrow = (WebDriverException) e;535 } else {536 toThrow = new SessionNotCreatedException(537 "Possible causes are invalid address of the remote server or browser start-up failure.", e);538 }539 } else if (e instanceof WebDriverException) {540 toThrow = (WebDriverException) e;541 } else {542 toThrow = new UnreachableBrowserException(543 "Error communicating with the remote browser. It may have died.", e);544 }545 populateWebDriverException(toThrow);546 toThrow.addInfo("Command", command.toString());547 throw toThrow;548 } finally {549 Thread.currentThread().setName(currentName);550 }551 try {552 errorHandler.throwIfResponseFailed(response, System.currentTimeMillis() - start);553 } catch (WebDriverException ex) {554 populateWebDriverException(ex);555 ex.addInfo("Command", command.toString());556 throw ex;557 }558 return response;559 }560 private void populateWebDriverException(WebDriverException ex) {561 ex.addInfo(WebDriverException.DRIVER_INFO, this.getClass().getName());562 if (getSessionId() != null) {563 ex.addInfo(WebDriverException.SESSION_ID, getSessionId().toString());564 }565 if (getCapabilities() != null) {566 ex.addInfo("Capabilities", getCapabilities().toString());567 }568 }569 protected Response execute(String driverCommand, Map<String, ?> parameters) {570 return execute(new CommandPayload(driverCommand, parameters));571 }572 protected Response execute(String command) {573 return execute(command, ImmutableMap.of());574 }575 protected ExecuteMethod getExecuteMethod() {576 return executeMethod;577 }578 @Override579 public void perform(Collection<Sequence> actions) {580 execute(DriverCommand.ACTIONS(actions));581 }582 @Override583 public void resetInputState() {584 execute(DriverCommand.CLEAR_ACTIONS_STATE);585 }586 @Override587 public Keyboard getKeyboard() {588 return keyboard;589 }590 @Override591 public Mouse getMouse() {592 return mouse;593 }594 @Override595 public VirtualAuthenticator addVirtualAuthenticator(VirtualAuthenticatorOptions options) {596 String authenticatorId = (String)597 execute(DriverCommand.ADD_VIRTUAL_AUTHENTICATOR, options.toMap()).getValue();598 return new RemoteVirtualAuthenticator(authenticatorId);599 }600 @Override601 public void removeVirtualAuthenticator(VirtualAuthenticator authenticator) {602 execute(DriverCommand.REMOVE_VIRTUAL_AUTHENTICATOR,603 ImmutableMap.of("authenticatorId", authenticator.getId()));604 }605 /**606 * Override this to be notified at key points in the execution of a command.607 *608 * @param sessionId the session id.609 * @param commandName the command that is being executed.610 * @param toLog any data that might be interesting.611 * @param when verb tense of "Execute" to prefix message612 */613 protected void log(SessionId sessionId, String commandName, Object toLog, When when) {614 if (!logger.isLoggable(level)) {615 return;616 }617 String text = String.valueOf(toLog);618 if (commandName.equals(DriverCommand.EXECUTE_SCRIPT)619 || commandName.equals(DriverCommand.EXECUTE_ASYNC_SCRIPT)) {620 if (text.length() > 100 && Boolean.getBoolean("webdriver.remote.shorten_log_messages")) {621 text = text.substring(0, 100) + "...";622 }623 }624 switch(when) {625 case BEFORE:626 logger.log(level, "Executing: " + commandName + " " + text);627 break;628 case AFTER:629 logger.log(level, "Executed: " + text);630 break;631 case EXCEPTION:632 logger.log(level, "Exception: " + text);633 break;634 default:635 logger.log(level, text);636 break;637 }638 }639 public FileDetector getFileDetector() {640 return fileDetector;641 }642 protected class RemoteWebDriverOptions implements Options {643 @Override644 @Beta645 public Logs logs() {646 return remoteLogs;647 }648 @Override649 public void addCookie(Cookie cookie) {650 cookie.validate();651 execute(DriverCommand.ADD_COOKIE(cookie));652 }653 @Override654 public void deleteCookieNamed(String name) {655 execute(DriverCommand.DELETE_COOKIE(name));656 }657 @Override658 public void deleteCookie(Cookie cookie) {659 deleteCookieNamed(cookie.getName());660 }661 @Override662 public void deleteAllCookies() {663 execute(DriverCommand.DELETE_ALL_COOKIES);664 }665 @Override666 @SuppressWarnings({"unchecked"})667 public Set<Cookie> getCookies() {668 Object returned = execute(DriverCommand.GET_ALL_COOKIES).getValue();669 Set<Cookie> toReturn = new HashSet<>();670 if (!(returned instanceof Collection)) {671 return toReturn;672 }673 ((Collection<?>) returned).stream()674 .map(o -> (Map<String, Object>) o)675 .map(rawCookie -> {676 // JSON object keys are defined in677 // https://w3c.github.io/webdriver/#dfn-table-for-cookie-conversion.678 Cookie.Builder builder =679 new Cookie.Builder((String) rawCookie.get("name"), (String) rawCookie.get("value"))680 .path((String) rawCookie.get("path"))681 .domain((String) rawCookie.get("domain"))682 .isSecure(rawCookie.containsKey("secure") && (Boolean) rawCookie.get("secure"))683 .isHttpOnly(684 rawCookie.containsKey("httpOnly") && (Boolean) rawCookie.get("httpOnly"))685 .sameSite((String) rawCookie.get("sameSite"));686 Number expiryNum = (Number) rawCookie.get("expiry");687 builder.expiresOn(expiryNum == null ? null : new Date(SECONDS.toMillis(expiryNum.longValue())));688 return builder.build();689 })690 .forEach(toReturn::add);691 return toReturn;692 }693 @Override694 public Cookie getCookieNamed(String name) {695 Set<Cookie> allCookies = getCookies();696 for (Cookie cookie : allCookies) {697 if (cookie.getName().equals(name)) {698 return cookie;699 }700 }701 return null;702 }703 @Override704 public Timeouts timeouts() {705 return new RemoteTimeouts();706 }707 @Override708 public ImeHandler ime() {709 return new RemoteInputMethodManager();710 }711 @Override712 @Beta713 public Window window() {714 return new RemoteWindow();715 }716 protected class RemoteInputMethodManager implements WebDriver.ImeHandler {717 @Override718 @SuppressWarnings("unchecked")719 public List<String> getAvailableEngines() {720 Response response = execute(DriverCommand.IME_GET_AVAILABLE_ENGINES);721 return (List<String>) response.getValue();722 }723 @Override724 public String getActiveEngine() {725 Response response = execute(DriverCommand.IME_GET_ACTIVE_ENGINE);726 return (String) response.getValue();727 }728 @Override729 public boolean isActivated() {730 Response response = execute(DriverCommand.IME_IS_ACTIVATED);731 return (Boolean) response.getValue();732 }733 @Override734 public void deactivate() {735 execute(DriverCommand.IME_DEACTIVATE);736 }737 @Override738 public void activateEngine(String engine) {739 execute(DriverCommand.IME_ACTIVATE_ENGINE(engine));740 }741 } // RemoteInputMethodManager class742 protected class RemoteTimeouts implements Timeouts {743 @Deprecated744 @Override745 public Timeouts implicitlyWait(long time, TimeUnit unit) {746 return implicitlyWait(Duration.ofMillis(unit.toMillis(time)));747 }748 @Override749 public Timeouts implicitlyWait(Duration duration) {750 execute(DriverCommand.SET_IMPLICIT_WAIT_TIMEOUT(duration));751 return this;752 }753 @Override754 public Duration getImplicitWaitTimeout() {755 Response response = execute(DriverCommand.GET_TIMEOUTS);756 Map<String, Object> rawSize = (Map<String, Object>) response.getValue();757 long timeout = ((Number) rawSize.get("implicit")).longValue();758 return Duration.ofMillis(timeout);759 }760 @Deprecated761 @Override762 public Timeouts setScriptTimeout(long time, TimeUnit unit) {763 return setScriptTimeout(Duration.ofMillis(unit.toMillis(time)));764 }765 @Override766 public Timeouts setScriptTimeout(Duration duration) {767 return scriptTimeout(duration);768 }769 @Override770 public Timeouts scriptTimeout(Duration duration) {771 execute(DriverCommand.SET_SCRIPT_TIMEOUT(duration));772 return this;773 }774 @Override775 public Duration getScriptTimeout() {776 Response response = execute(DriverCommand.GET_TIMEOUTS);777 Map<String, Object> rawSize = (Map<String, Object>) response.getValue();778 long timeout = ((Number) rawSize.get("script")).longValue();779 return Duration.ofMillis(timeout);780 }781 @Deprecated782 @Override783 public Timeouts pageLoadTimeout(long time, TimeUnit unit) {784 return pageLoadTimeout(Duration.ofMillis(unit.toMillis(time)));785 }786 @Override787 public Timeouts pageLoadTimeout(Duration duration) {788 execute(DriverCommand.SET_PAGE_LOAD_TIMEOUT(duration));789 return this;790 }791 @Override792 public Duration getPageLoadTimeout() {793 Response response = execute(DriverCommand.GET_TIMEOUTS);794 Map<String, Object> rawSize = (Map<String, Object>) response.getValue();795 long timeout = ((Number) rawSize.get("pageLoad")).longValue();796 return Duration.ofMillis(timeout);797 }798 } // timeouts class.799 @Beta800 protected class RemoteWindow implements Window {801 @Override802 public void setSize(Dimension targetSize) {803 execute(DriverCommand.SET_CURRENT_WINDOW_SIZE(targetSize));804 }805 @Override806 public void setPosition(Point targetPosition) {807 execute(DriverCommand.SET_CURRENT_WINDOW_POSITION(targetPosition));808 }809 @Override810 @SuppressWarnings({"unchecked"})811 public Dimension getSize() {812 Response response = execute(DriverCommand.GET_CURRENT_WINDOW_SIZE);813 Map<String, Object> rawSize = (Map<String, Object>) response.getValue();814 int width = ((Number) rawSize.get("width")).intValue();815 int height = ((Number) rawSize.get("height")).intValue();816 return new Dimension(width, height);817 }818 Map<String, Object> rawPoint;819 @Override820 @SuppressWarnings("unchecked")821 public Point getPosition() {822 Response response = execute(DriverCommand.GET_CURRENT_WINDOW_POSITION());823 rawPoint = (Map<String, Object>) response.getValue();824 int x = ((Number) rawPoint.get("x")).intValue();825 int y = ((Number) rawPoint.get("y")).intValue();826 return new Point(x, y);827 }828 @Override829 public void maximize() {830 execute(DriverCommand.MAXIMIZE_CURRENT_WINDOW);831 }832 @Override833 public void minimize() {834 execute(DriverCommand.MINIMIZE_CURRENT_WINDOW);835 }836 @Override837 public void fullscreen() {838 execute(DriverCommand.FULLSCREEN_CURRENT_WINDOW);839 }840 }841 }842 private class RemoteNavigation implements Navigation {843 @Override844 public void back() {845 execute(DriverCommand.GO_BACK);846 }847 @Override848 public void forward() {849 execute(DriverCommand.GO_FORWARD);850 }851 @Override852 public void to(String url) {853 get(url);854 }855 @Override856 public void to(URL url) {857 get(String.valueOf(url));858 }859 @Override860 public void refresh() {861 execute(DriverCommand.REFRESH);862 }863 }864 protected class RemoteTargetLocator implements TargetLocator {865 @Override866 public WebDriver frame(int frameIndex) {867 execute(DriverCommand.SWITCH_TO_FRAME(frameIndex));868 return RemoteWebDriver.this;869 }870 @Override871 public WebDriver frame(String frameName) {872 String name = frameName.replaceAll("(['\"\\\\#.:;,!?+<>=~*^$|%&@`{}\\-/\\[\\]\\(\\)])", "\\\\$1");873 List<WebElement> frameElements = RemoteWebDriver.this.findElements(874 By.cssSelector("frame[name='" + name + "'],iframe[name='" + name + "']"));875 if (frameElements.size() == 0) {876 frameElements = RemoteWebDriver.this.findElements(877 By.cssSelector("frame#" + name + ",iframe#" + name));878 }879 if (frameElements.size() == 0) {880 throw new NoSuchFrameException("No frame element found by name or id " + frameName);881 }882 return frame(frameElements.get(0));883 }884 @Override885 public WebDriver frame(WebElement frameElement) {886 Object elementAsJson = new WebElementToJsonConverter().apply(frameElement);887 execute(DriverCommand.SWITCH_TO_FRAME(elementAsJson));888 return RemoteWebDriver.this;889 }890 @Override891 public WebDriver parentFrame() {892 execute(DriverCommand.SWITCH_TO_PARENT_FRAME);893 return RemoteWebDriver.this;894 }895 @Override896 public WebDriver window(String windowHandleOrName) {897 try {898 execute(DriverCommand.SWITCH_TO_WINDOW(windowHandleOrName));899 return RemoteWebDriver.this;900 } catch (NoSuchWindowException nsw) {901 // simulate search by name902 String original = getWindowHandle();903 for (String handle : getWindowHandles()) {904 switchTo().window(handle);905 if (windowHandleOrName.equals(executeScript("return window.name"))) {906 return RemoteWebDriver.this; // found by name907 }908 }909 switchTo().window(original);910 throw nsw;911 }912 }913 @Override914 public WebDriver newWindow(WindowType typeHint) {915 String original = getWindowHandle();916 try {917 Response response = execute(DriverCommand.SWITCH_TO_NEW_WINDOW(typeHint));918 String newWindowHandle = ((Map<String, Object>) response.getValue()).get("handle").toString();919 switchTo().window(newWindowHandle);920 return RemoteWebDriver.this;921 } catch (WebDriverException ex) {922 switchTo().window(original);923 throw ex;924 }925 }926 @Override927 public WebDriver defaultContent() {928 execute(DriverCommand.SWITCH_TO_FRAME(null));929 return RemoteWebDriver.this;930 }931 @Override932 public WebElement activeElement() {933 Response response = execute(DriverCommand.GET_ACTIVE_ELEMENT);934 return (WebElement) response.getValue();935 }936 @Override937 public Alert alert() {938 execute(DriverCommand.GET_ALERT_TEXT);939 return new RemoteAlert();940 }941 }942 private class RemoteAlert implements Alert {943 public RemoteAlert() {944 }945 @Override946 public void dismiss() {947 execute(DriverCommand.DISMISS_ALERT);948 }949 @Override950 public void accept() {951 execute(DriverCommand.ACCEPT_ALERT);952 }953 @Override954 public String getText() {955 return (String) execute(DriverCommand.GET_ALERT_TEXT).getValue();956 }957 /**958 * @param keysToSend character sequence to send to the alert959 *960 * @throws IllegalArgumentException if keysToSend is null961 */962 @Override963 public void sendKeys(String keysToSend) {964 if(keysToSend==null) {965 throw new IllegalArgumentException("Keys to send should be a not null CharSequence");966 }967 execute(DriverCommand.SET_ALERT_VALUE(keysToSend));968 }969 }970 private class RemoteVirtualAuthenticator implements VirtualAuthenticator {971 private final String id;972 public RemoteVirtualAuthenticator(final String id) {973 this.id = Require.nonNull("Id", id);974 }975 @Override976 public String getId() {977 return id;978 }979 @Override980 public void addCredential(Credential credential) {981 execute(DriverCommand.ADD_CREDENTIAL,982 new ImmutableMap.Builder<String, Object>()983 .putAll(credential.toMap())984 .put("authenticatorId", id)985 .build());986 }987 @Override988 public List<Credential> getCredentials() {989 List<Map<String, Object>> response = (List<Map<String, Object>>)990 execute(DriverCommand.GET_CREDENTIALS, ImmutableMap.of("authenticatorId", id)).getValue();991 return response.stream().map(Credential::fromMap).collect(Collectors.toList());992 }993 @Override994 public void removeCredential(byte[] credentialId) {995 removeCredential(Base64.getUrlEncoder().encodeToString(credentialId));996 }997 @Override998 public void removeCredential(String credentialId) {999 execute(DriverCommand.REMOVE_CREDENTIAL,1000 ImmutableMap.of("authenticatorId", id, "credentialId", credentialId));1001 }1002 @Override1003 public void removeAllCredentials() {1004 execute(DriverCommand.REMOVE_ALL_CREDENTIALS, ImmutableMap.of("authenticatorId", id));1005 }1006 @Override1007 public void setUserVerified(boolean verified) {1008 execute(DriverCommand.SET_USER_VERIFIED,1009 ImmutableMap.of("authenticatorId", id, "isUserVerified", verified));1010 }1011 }1012 public enum When {1013 BEFORE,1014 AFTER,1015 EXCEPTION1016 }1017 @Override1018 public String toString() {1019 Capabilities caps = getCapabilities();1020 if (caps == null) {1021 return super.toString();1022 }1023 // w3c name first1024 Object platform = caps.getCapability(PLATFORM_NAME);1025 if (!(platform instanceof String)) {1026 platform = caps.getCapability(PLATFORM);1027 }1028 if (platform == null) {1029 platform = "unknown";1030 }1031 return String.format(1032 "%s: %s on %s (%s)",1033 getClass().getSimpleName(),1034 caps.getBrowserName(),1035 platform,1036 getSessionId());1037 }1038 private enum Mechanism {1039 CONTEXT {1040 @Override1041 WebElement findElement(RemoteWebDriver parent, SearchContext context, By locator) {1042 return locator.findElement(context);1043 }1044 @Override1045 List<WebElement> findElements(RemoteWebDriver parent, SearchContext context, By locator) {1046 return locator.findElements(context);1047 }1048 },1049 REMOTE {1050 @Override1051 WebElement findElement(RemoteWebDriver parent, SearchContext context, By locator) {1052 String commandName;1053 Map<String, Object> params = new HashMap<>();1054 By.Remotable.Parameters fromLocator = ((By.Remotable) locator).getRemoteParameters();1055 params.put("using", fromLocator.using());1056 params.put("value", fromLocator.value());1057 if (context instanceof RemoteWebElement) {1058 commandName = DriverCommand.FIND_CHILD_ELEMENT;1059 params.put("id", ((RemoteWebElement) context).getId());1060 } else {1061 commandName = DriverCommand.FIND_ELEMENT;1062 }1063 Response response = parent.execute(new CommandPayload(commandName, params));1064 Object value = response.getValue();1065 if (value == null) {1066 throw new NoSuchElementException("Unable to find element with locator " + locator);1067 }1068 try {1069 return (WebElement) value;1070 } catch (ClassCastException ex) {1071 throw new WebDriverException(1072 "Returned value cannot be converted to WebElement: " + value, ex);1073 }1074 }1075 @Override1076 List<WebElement> findElements(RemoteWebDriver parent, SearchContext context, By locator) {1077 String commandName;1078 Map<String, Object> params = new HashMap<>();1079 By.Remotable.Parameters fromLocator = ((By.Remotable) locator).getRemoteParameters();1080 params.put("using", fromLocator.using());1081 params.put("value", fromLocator.value());1082 if (context instanceof RemoteWebElement) {1083 commandName = DriverCommand.FIND_CHILD_ELEMENTS;1084 params.put("id", ((RemoteWebElement) context).getId());1085 } else {1086 commandName = DriverCommand.FIND_ELEMENTS;1087 }1088 Response response = parent.execute(new CommandPayload(commandName, params));1089 Object value = response.getValue();1090 if (value == null) { // see https://github.com/SeleniumHQ/selenium/issues/45551091 return Collections.emptyList();1092 }1093 try {...
Source:ElementLocation.java
...136 RemoteWebDriver driver,137 SearchContext context,138 BiFunction<String, Object, CommandPayload> createPayload,139 By locator) {140 By.Remotable.Parameters params = ((By.Remotable) locator).getRemoteParameters();141 CommandPayload commandPayload = createPayload.apply(params.using(), params.value());142 Response response = driver.execute(commandPayload);143 WebElement element = (WebElement) response.getValue();144 if (element == null) {145 throw new NoSuchElementException("Unable to find element with locator " + locator);146 }147 return massage(driver, context, element, locator);148 }149 @Override150 List<WebElement> findElements(151 RemoteWebDriver driver,152 SearchContext context,153 BiFunction<String, Object, CommandPayload> createPayload,154 By locator) {155 By.Remotable.Parameters params = ((By.Remotable) locator).getRemoteParameters();156 CommandPayload commandPayload = createPayload.apply(params.using(), params.value());157 Response response = driver.execute(commandPayload);158 @SuppressWarnings("unchecked") List<WebElement> elements = (List<WebElement>) response.getValue();159 if (elements == null) { // see https://github.com/SeleniumHQ/selenium/issues/4555160 return Collections.emptyList();161 }162 return elements.stream()163 .map(e -> massage(driver, context, e, locator))164 .collect(Collectors.toList());165 }166 }167 ;168 abstract WebElement findElement(169 RemoteWebDriver driver,170 SearchContext context,171 BiFunction<String, Object, CommandPayload> createPayload,172 By locator);173 abstract List<WebElement> findElements(174 RemoteWebDriver driver,175 SearchContext context,176 BiFunction<String, Object, CommandPayload> createPayload,177 By locator);178 protected WebElement massage(RemoteWebDriver driver, SearchContext context, WebElement element, By locator) {179 if (!(element instanceof RemoteWebElement)) {180 return element;181 }182 RemoteWebElement remoteElement = (RemoteWebElement) element;183 if (locator instanceof By.Remotable) {184 By.Remotable.Parameters params = ((By.Remotable) locator).getRemoteParameters();185 remoteElement.setFoundBy(context, params.using(), String.valueOf(params.value()));186 }187 remoteElement.setFileDetector(driver.getFileDetector());188 remoteElement.setParent(driver);189 return remoteElement;190 }191 }192}...
Source:ByShadow.java
...36public class ByShadow extends By implements By.Remotable {37 private final By target;38 private final String shadowHost;39 private final String[] innerShadowHosts;40 private final By.Remotable.Parameters params;41 protected ByShadow(By target, String shadowHost, String[] innerShadowHosts) {42 this.target = target;43 this.shadowHost = shadowHost;44 this.innerShadowHosts = innerShadowHosts;45 this.params = new By.Remotable.Parameters("shadow dom locator", target + " inside shadow dom located by " + shadowHost);46 }47 public static ByShadow cssSelector(String target, String shadowHost, String... innerShadowHosts) {48 return new ByShadow(By.cssSelector(target), shadowHost, innerShadowHosts);49 }50 public static ByShadow cssSelector(By target, String shadowHost, String... innerShadowHosts) {51 return new ByShadow(target, shadowHost, innerShadowHosts);52 }53 @Override54 public String toString() {55 List<String> allRoots = new ArrayList<>();56 allRoots.add(shadowHost);57 for(String innerHost : innerShadowHosts) {58 allRoots.add(innerHost);59 }...
By.Remotable.Parameters
Using AI Code Generation
1package com.automation.selenium.core;2import org.openqa.selenium.By;3public class ByRemotableParameters {4public static void main(String[] args) {5By by = By.remotable("custom", new By.Remotable.Parameters("id", "name"));6System.out.println(by.toString());7}8}9package com.automation.selenium.core;10import org.openqa.selenium.By;11public class ByRemotableParameters {12public static void main(String[] args) {13By by = By.remotable("custom", new By.Remotable.Parameters("id", "name"));14System.out.println(by.toString());15}16}17package com.automation.selenium.core;18import org.openqa.selenium.By;19public class ByRemotableParameters {20public static void main(String[] args) {21By by = By.remotable("custom", new By.Remotable.Parameters("id", "name"));22System.out.println(by.toString());23}24}25package com.automation.selenium.core;26import org.openqa.selenium.By;27public class ByRemotableParameters {
By.Remotable.Parameters
Using AI Code Generation
1import org.openqa.selenium.By;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.WebElement;4import org.openqa.selenium.chrome.ChromeDriver;5import org.openqa.selenium.remote.RemoteWebElement;6import org.openqa.selenium.support.ByIdOrName;7import org.openqa.selenium.support.pagefactory.ByAll;8import org.openqa.selenium.support.pagefactory.ByChained;9import org.openqa.selenium.support.pagefactory.ByAll;10import org.openqa.selenium.support.pagefactory.ByAll;11import org.openqa.selenium.support.pagefactory.ByAll;12import org.openqa.selenium.support.pagefactory.ByAll;13import org.openqa.selenium.support.pagefactory.ByAll;14import org.openqa.selenium.support.pagefactory.ByAll;15import org.openqa.selenium.support.pagefactory.ByAll;16import org.openqa.selenium.support.pagefactory.ByAll;17import org.openqa.selenium.support.pagefactory.ByAll;18import java.util.List;19import java.util.concurrent.TimeUnit;20public class ByRemotableParameters {21 public static void main(String[] args) {22 WebDriver driver = new ChromeDriver();23 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);24 WebElement element = driver.findElement(By.id("lst-ib"));25 element.sendKeys("Selenium");26 element.submit();27 WebElement element2 = driver.findElement(By.name("q"));28 element2.sendKeys("Selenium");29 element2.submit();30 WebElement element3 = driver.findElement(By.className("lsb"));31 element3.click();32 List<WebElement> element4 = driver.findElements(By.tagName("a"));33 System.out.println(element4.size());34 WebElement element5 = driver.findElement(By.linkText("Selenium - Web Browser Automation"));35 element5.click();36 WebElement element6 = driver.findElement(By.partialLinkText("Selenium"));37 element6.click();38 element7.sendKeys("Selenium");39 element7.submit();40 WebElement element8 = driver.findElement(By.cssSelector("#lst-ib"));41 element8.sendKeys("Selenium");42 element8.submit();43 By all = new ByAll(By.id("lst-ib"), By.name("q"));
By.Remotable.Parameters
Using AI Code Generation
1import org.openqa.selenium.By;2import org.openqa.selenium.WebElement;3import org.openqa.selenium.remote.RemoteWebDriver;4import org.openqa.selenium.remote.DesiredCapabilities;5import org.openqa.selenium.remote.RemoteWebElement;6import org.openqa.selenium.remote.By.RemoteParameters;7import org.openqa.selenium.remote.By.RemoteParameters.ByRemote;8import org.openqa.selenium.remote.By.RemoteParameters.ByRemote.ByRemoteClass;9import org.openqa.selenium.remote.By.RemoteParameters.ByRemote.ByRemoteId;10import org.openqa.selenium.remote.By.RemoteParameters.ByRemote.ByRemoteName;11import org.openqa.selenium.remote.By.RemoteParameters.ByRemote.ByRemoteTagName;12import org.openqa.selenium.remote.By.RemoteParameters.ByRemote.ByRemoteXpath;13public class RemoteBy {14 public static ByRemoteClass className(String className) {15 return new ByRemoteClass(className);16 }17 public static ByRemoteId id(String id) {18 return new ByRemoteId(id);19 }20 public static ByRemoteName name(String name) {21 return new ByRemoteName(name);22 }23 public static ByRemoteTagName tagName(String tagName) {24 return new ByRemoteTagName(tagName);25 }26 public static ByRemoteXpath xpath(String xpathExpression) {27 return new ByRemoteXpath(xpathExpression);28 }29}30public class RemoteByExample {31 public static void main(String[] args) {32 RemoteWebDriver driver = new RemoteWebDriver(33 DesiredCapabilities.chrome());34 WebElement element = driver.findElement(RemoteBy.className("class"));35 element = driver.findElement(RemoteBy.id("id"));36 element = driver.findElement(RemoteBy.name("name"));37 element = driver.findElement(RemoteBy.tagName("tag"));38 driver.quit();39 }40}
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!!