How to use value method of org.openqa.selenium.By.Remotable.Parameters class

Best Selenium code snippet using org.openqa.selenium.By.Remotable.Parameters.value

Source:RemoteWebDriver.java Github

copy

Full Screen

...280 }281 @Override282 public String getTitle() {283 Response response = execute(DriverCommand.GET_TITLE);284 Object value = response.getValue();285 return value == null ? "" : value.toString();286 }287 @Override288 public String getCurrentUrl() {289 Response response = execute(DriverCommand.GET_CURRENT_URL);290 if (response == null || response.getValue() == null) {291 throw new WebDriverException("Remote browser did not respond to getCurrentUrl");292 }293 return response.getValue().toString();294 }295 @Override296 public <X> X getScreenshotAs(OutputType<X> outputType) throws WebDriverException {297 Response response = execute(DriverCommand.SCREENSHOT);298 Object result = response.getValue();299 if (result instanceof String) {300 String base64EncodedPng = (String) result;301 return outputType.convertFromBase64Png(base64EncodedPng);302 } else if (result instanceof byte[]) {303 return outputType.convertFromPngBytes((byte[]) result);304 } else {305 throw new RuntimeException(String.format("Unexpected result for %s command: %s",306 DriverCommand.SCREENSHOT,307 result == null ? "null" : result.getClass().getName() + " instance"));308 }309 }310 @Override311 public Pdf print(PrintOptions printOptions) throws WebDriverException {312 Response response = execute(DriverCommand.PRINT_PAGE(printOptions));313 Object result = response.getValue();314 return new Pdf((String) result);315 }316 @Override317 public WebElement findElement(By locator) {318 Require.nonNull("Locator", locator);319 return findElement(this, this, locator);320 }321 WebElement findElement(RemoteWebDriver parent, SearchContext context, By locator) {322 Mechanism mechanism = remotableBys.get(locator.getClass());323 if (mechanism != null) {324 WebElement element = mechanism.findElement(parent, context, locator);325 return massage(parent, context, element, locator);326 }327 // Attempt to find the element remotely328 if (locator instanceof By.Remotable) {329 try {330 WebElement element = Mechanism.REMOTE.findElement(parent, context, locator);331 remotableBys.put(locator.getClass(), Mechanism.REMOTE);332 return massage(parent, context, element, locator);333 } catch (NoSuchElementException e) {334 remotableBys.put(locator.getClass(), Mechanism.REMOTE);335 throw e;336 } catch (InvalidArgumentException e) {337 // Fall through338 }339 }340 try {341 WebElement element = Mechanism.CONTEXT.findElement(parent, context, locator);342 remotableBys.put(locator.getClass(), Mechanism.CONTEXT);343 return massage(parent, context, element, locator);344 } catch (NoSuchElementException e) {345 remotableBys.put(locator.getClass(), Mechanism.CONTEXT);346 throw e;347 }348 }349 @Override350 public List<WebElement> findElements(By locator) {351 Require.nonNull("Locator", locator);352 return findElements(this, this, locator);353 }354 public List<WebElement> findElements(RemoteWebDriver parent, SearchContext context, By locator) {355 Mechanism mechanism = remotableBys.get(locator.getClass());356 if (mechanism != null) {357 List<WebElement> elements = mechanism.findElements(parent, context, locator);358 elements.forEach(e -> massage(parent, context, e, locator));359 return elements;360 }361 // Attempt to find the element remotely362 if (locator instanceof By.Remotable) {363 try {364 List<WebElement> elements = Mechanism.REMOTE.findElements(parent, context, locator);365 remotableBys.put(locator.getClass(), Mechanism.REMOTE);366 elements.forEach(e -> massage(parent, context, e, locator));367 return elements;368 } catch (NoSuchElementException e) {369 remotableBys.put(locator.getClass(), Mechanism.REMOTE);370 throw e;371 } catch (InvalidArgumentException e) {372 // Fall through373 }374 }375 try {376 List<WebElement> elements = Mechanism.CONTEXT.findElements(parent, context, locator);377 remotableBys.put(locator.getClass(), Mechanism.CONTEXT);378 elements.forEach(e -> massage(parent, context, e, locator));379 return elements;380 } catch (NoSuchElementException e) {381 remotableBys.put(locator.getClass(), Mechanism.CONTEXT);382 throw e;383 }384 }385 private WebElement massage(RemoteWebDriver parent, SearchContext context, WebElement element, By locator) {386 if (!(element instanceof RemoteWebElement)) {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 {1094 @SuppressWarnings("unchecked") List<WebElement> toReturn = (List<WebElement>) value;1095 return toReturn;1096 } catch (ClassCastException ex) {1097 throw new WebDriverException(1098 "Returned value cannot be converted to WebElement: " + value, ex);1099 }1100 }1101 }1102 ;1103 abstract WebElement findElement(RemoteWebDriver parent, SearchContext context, By locator);1104 abstract List<WebElement> findElements(RemoteWebDriver parent, SearchContext context, By locator);1105 }1106}...

Full Screen

Full Screen

Source:ElementLocation.java Github

copy

Full Screen

...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}...

Full Screen

Full Screen

value

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.By;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.WebElement;4import org.openqa.selenium.firefox.FirefoxDriver;5import java.util.List;6public class FindElements {7 public static void main(String[] args) throws InterruptedException {8 WebDriver driver = new FirefoxDriver();9 driver.manage().window().maximize();10 Thread.sleep(3000);11 List<WebElement> linkElements = driver.findElements(By.tagName("a"));12 System.out.println(linkElements.size());13 for (WebElement e : linkElements) {14 System.out.println(e.getText());15 }16 driver.close();17 }18}19By.className()20public static By className(String className)21import org.openqa.selenium.By;22import org.openqa.selenium.WebDriver;23import org.openqa.selenium.WebElement;24import org.openqa.selenium.firefox.FirefoxDriver;25import java.util.List;26public class FindElements {27 public static void main(String[] args) throws InterruptedException {28 WebDriver driver = new FirefoxDriver();29 driver.manage().window().maximize();30 Thread.sleep(3000);31 List<WebElement> linkElements = driver.findElements(By.className("gb_P"));32 System.out.println(linkElements.size());33 for (WebElement e : linkElements) {34 System.out.println(e.getText());35 }36 driver.close();37 }38}

Full Screen

Full Screen

value

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.By;2By by = By.cssSelector("input[placeholder='Search']");3System.out.println(by.value());4import org.openqa.selenium.By;5By by = By.cssSelector("input[placeholder='Search']");6System.out.println(by.value());7import org.openqa.selenium.By;8By by = By.cssSelector("input[placeholder='Search']");9System.out.println(by.value());10import org.openqa.selenium.By;11By by = By.cssSelector("input[placeholder='Search']");12System.out.println(by.value());13import org.openqa.selenium.By;14By by = By.cssSelector("input[placeholder='Search']");15System.out.println(by.value());16import org.openqa.selenium.By;17By by = By.cssSelector("input[placeholder='Search']");18System.out.println(by.value());19import org.openqa.selenium.By;20By by = By.cssSelector("input[placeholder='Search']");21System.out.println(by.value());22import org.openqa.selenium.By;23By by = By.cssSelector("input[placeholder='Search']");24System.out.println(by.value());25import org.openqa.selenium.By;26By by = By.cssSelector("input[placeholder='Search']");27System.out.println(by.value());28import org.openqa.selenium.By;29By by = By.cssSelector("input[placeholder='Search']");30System.out.println(by.value());

Full Screen

Full Screen

value

Using AI Code Generation

copy

Full Screen

1package com.seleniumsimplified.webdriver;2import org.openqa.selenium.By;3import org.openqa.selenium.WebDriver;4import org.openqa.selenium.WebElement;5import org.openqa.selenium.firefox.FirefoxDriver;6public class WebElementDemo {7 public static void main(String[] args) {8 WebDriver driver = new FirefoxDriver();9 "basic_web_page.html");10 WebElement para1 = driver.findElement(By.id("para1"));11 System.out.println(para1.getText());12 WebElement para2 = driver.findElement(By.id("para2"));13 System.out.println(para2.getText());14 WebElement para3 = driver.findElement(By.id("para3"));15 System.out.println(para3.getText());16 driver.quit();17 }18}

Full Screen

Full Screen

Selenium 4 Tutorial:

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.

Chapters:

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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.

  6. 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.

  7. 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.

Selenium 101 certifications:

LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.

Run Selenium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in By.Remotable.Parameters

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful