Best Selenium code snippet using org.openqa.selenium.Cookie.getValue
Source:RemoteWebDriver.java  
...176  }177  protected void startSession(Capabilities capabilities) {178    Map<String, ?> parameters = ImmutableMap.of("desiredCapabilities", capabilities);179    Response response = execute(DriverCommand.NEW_SESSION, parameters);180    Map<String, Object> rawCapabilities = (Map<String, Object>) response.getValue();181    MutableCapabilities returnedCapabilities = new MutableCapabilities();182    for (Map.Entry<String, Object> entry : rawCapabilities.entrySet()) {183      // Handle the platform later184      if (PLATFORM.equals(entry.getKey()) || PLATFORM_NAME.equals(entry.getKey())) {185        continue;186      }187      returnedCapabilities.setCapability(entry.getKey(), entry.getValue());188    }189    String platformString = (String) rawCapabilities.getOrDefault(PLATFORM,190                                                                  rawCapabilities.get(PLATFORM_NAME));191    Platform platform;192    try {193      if (platformString == null || "".equals(platformString)) {194        platform = Platform.ANY;195      } else {196        platform = Platform.fromString(platformString);197      }198    } catch (WebDriverException e) {199      // The server probably responded with a name matching the os.name200      // system property. Try to recover and parse this.201      platform = Platform.extractFromSysProperty(platformString);202    }203    returnedCapabilities.setCapability(PLATFORM, platform);204    returnedCapabilities.setCapability(PLATFORM_NAME, platform);205    if (rawCapabilities.containsKey(SUPPORTS_JAVASCRIPT)) {206      Object raw = rawCapabilities.get(SUPPORTS_JAVASCRIPT);207      if (raw instanceof String) {208        returnedCapabilities.setCapability(SUPPORTS_JAVASCRIPT, Boolean.parseBoolean((String) raw));209      } else if (raw instanceof Boolean) {210        returnedCapabilities.setCapability(SUPPORTS_JAVASCRIPT, ((Boolean) raw).booleanValue());211      }212    } else {213      returnedCapabilities.setCapability(SUPPORTS_JAVASCRIPT, true);214    }215    this.capabilities = returnedCapabilities;216    sessionId = new SessionId(response.getSessionId());217  }218  public ErrorHandler getErrorHandler() {219    return errorHandler;220  }221  public void setErrorHandler(ErrorHandler handler) {222    this.errorHandler = handler;223  }224  public CommandExecutor getCommandExecutor() {225    return executor;226  }227  protected void setCommandExecutor(CommandExecutor executor) {228    this.executor = executor;229  }230  public Capabilities getCapabilities() {231    return capabilities;232  }233  public void get(String url) {234    execute(DriverCommand.GET, ImmutableMap.of("url", url));235  }236  public String getTitle() {237    Response response = execute(DriverCommand.GET_TITLE);238    Object value = response.getValue();239    return value == null ? "" : value.toString();240  }241  public String getCurrentUrl() {242    Response response = execute(DriverCommand.GET_CURRENT_URL);243    if (response == null || response.getValue() == null) {244      throw new WebDriverException("Remote browser did not respond to getCurrentUrl");245    }246    return response.getValue().toString();247  }248  public <X> X getScreenshotAs(OutputType<X> outputType) throws WebDriverException {249    Response response = execute(DriverCommand.SCREENSHOT);250    Object result = response.getValue();251    if (result instanceof String) {252      String base64EncodedPng = (String) result;253      return outputType.convertFromBase64Png(base64EncodedPng);254    } else if (result instanceof byte[]) {255      String base64EncodedPng = new String((byte[]) result);256      return outputType.convertFromBase64Png(base64EncodedPng);257    } else {258      throw new RuntimeException(String.format("Unexpected result for %s command: %s",259          DriverCommand.SCREENSHOT,260          result == null ? "null" : result.getClass().getName() + " instance"));261    }262  }263  public List<WebElement> findElements(By by) {264    return by.findElements(this);265  }266  public WebElement findElement(By by) {267    return by.findElement(this);268  }269  protected WebElement findElement(String by, String using) {270    if (using == null) {271      throw new IllegalArgumentException("Cannot find elements when the selector is null.");272    }273    Response response = execute(DriverCommand.FIND_ELEMENT,274        ImmutableMap.of("using", by, "value", using));275    Object value = response.getValue();276    WebElement element;277    try {278      element = (WebElement) value;279    } catch (ClassCastException ex) {280      throw new WebDriverException("Returned value cannot be converted to WebElement: " + value, ex);281    }282    setFoundBy(this, element, by, using);283    return element;284  }285  protected void setFoundBy(SearchContext context, WebElement element, String by, String using) {286    if (element instanceof RemoteWebElement) {287      RemoteWebElement remoteElement = (RemoteWebElement) element;288      remoteElement.setFoundBy(context, by, using);289      remoteElement.setFileDetector(getFileDetector());290    }291  }292  @SuppressWarnings("unchecked")293  protected List<WebElement> findElements(String by, String using) {294    if (using == null) {295      throw new IllegalArgumentException("Cannot find elements when the selector is null.");296    }297    Response response = execute(DriverCommand.FIND_ELEMENTS,298        ImmutableMap.of("using", by, "value", using));299    Object value = response.getValue();300    if (value == null) { // see https://github.com/SeleniumHQ/selenium/issues/4555301      return Collections.emptyList();302    }303    List<WebElement> allElements;304    try {305      allElements = (List<WebElement>) value;306    } catch (ClassCastException ex) {307      throw new WebDriverException("Returned value cannot be converted to List<WebElement>: " + value, ex);308    }309    for (WebElement element : allElements) {310      setFoundBy(this, element, by, using);311    }312    return allElements;313  }314  public WebElement findElementById(String using) {315    return findElement("id", using);316  }317  public List<WebElement> findElementsById(String using) {318    return findElements("id", using);319  }320  public WebElement findElementByLinkText(String using) {321    return findElement("link text", using);322  }323  public List<WebElement> findElementsByLinkText(String using) {324    return findElements("link text", using);325  }326  public WebElement findElementByPartialLinkText(String using) {327    return findElement("partial link text", using);328  }329  public List<WebElement> findElementsByPartialLinkText(String using) {330    return findElements("partial link text", using);331  }332  public WebElement findElementByTagName(String using) {333    return findElement("tag name", using);334  }335  public List<WebElement> findElementsByTagName(String using) {336    return findElements("tag name", using);337  }338  public WebElement findElementByName(String using) {339    return findElement("name", using);340  }341  public List<WebElement> findElementsByName(String using) {342    return findElements("name", using);343  }344  public WebElement findElementByClassName(String using) {345    return findElement("class name", using);346  }347  public List<WebElement> findElementsByClassName(String using) {348    return findElements("class name", using);349  }350  public WebElement findElementByCssSelector(String using) {351    return findElement("css selector", using);352  }353  public List<WebElement> findElementsByCssSelector(String using) {354    return findElements("css selector", using);355  }356  public WebElement findElementByXPath(String using) {357    return findElement("xpath", using);358  }359  public List<WebElement> findElementsByXPath(String using) {360    return findElements("xpath", using);361  }362  // Misc363  public String getPageSource() {364    return (String) execute(DriverCommand.GET_PAGE_SOURCE).getValue();365  }366  public void close() {367    execute(DriverCommand.CLOSE);368  }369  public Response quit() {370    // no-op if session id is null. We're only going to make ourselves unhappy371    Response response=null;372    if (sessionId == null) {373      return response;374    }375    try {376      response=execute(DriverCommand.QUIT);377    } finally {378      sessionId = null;379    }380    return response;381  }382  @SuppressWarnings({"unchecked"})383  public Set<String> getWindowHandles() {384    Response response = execute(DriverCommand.GET_WINDOW_HANDLES);385    Object value = response.getValue();386    try {387      List<String> returnedValues = (List<String>) value;388      return new LinkedHashSet<>(returnedValues);389    } catch (ClassCastException ex) {390      throw new WebDriverException(391        "Returned value cannot be converted to List<String>: " + value, ex);392    }393  }394  public String getWindowHandle() {395    return String.valueOf(execute(DriverCommand.GET_CURRENT_WINDOW_HANDLE).getValue());396  }397  public Object executeScript(String script, Object... args) {398    if (!isJavascriptEnabled()) {399      throw new UnsupportedOperationException(400          "You must be using an underlying instance of WebDriver that supports executing javascript");401    }402    // Escape the quote marks403    script = script.replaceAll("\"", "\\\"");404    List<Object> convertedArgs = Stream.of(args).map(new WebElementToJsonConverter()).collect(405        Collectors.toList());406    Map<String, ?> params = ImmutableMap.of("script", script, "args", convertedArgs);407    return execute(DriverCommand.EXECUTE_SCRIPT, params).getValue();408  }409  public Object executeAsyncScript(String script, Object... args) {410    if (!isJavascriptEnabled()) {411      throw new UnsupportedOperationException("You must be using an underlying instance of " +412          "WebDriver that supports executing javascript");413    }414    // Escape the quote marks415    script = script.replaceAll("\"", "\\\"");416    List<Object> convertedArgs = Stream.of(args).map(new WebElementToJsonConverter()).collect(417        Collectors.toList());418    Map<String, ?> params = ImmutableMap.of("script", script, "args", convertedArgs);419    return execute(DriverCommand.EXECUTE_ASYNC_SCRIPT, params).getValue();420  }421  private boolean isJavascriptEnabled() {422    return capabilities.is(SUPPORTS_JAVASCRIPT);423  }424  public TargetLocator switchTo() {425    return new RemoteTargetLocator();426  }427  public Navigation navigate() {428    return new RemoteNavigation();429  }430  public Options manage() {431    return new RemoteWebDriverOptions();432  }433  protected void setElementConverter(JsonToWebElementConverter converter) {434    this.converter = Objects.requireNonNull(converter, "Element converter must not be null");435  }436  protected JsonToWebElementConverter getElementConverter() {437    return converter;438  }439  /**440   * Sets the RemoteWebDriver's client log level.441   *442   * @param level The log level to use.443   */444  public void setLogLevel(Level level) {445    this.level = level;446  }447  protected Response execute(String driverCommand, Map<String, ?> parameters) {448    Command command = new Command(sessionId, driverCommand, parameters);449    Response response;450    long start = System.currentTimeMillis();451    String currentName = Thread.currentThread().getName();452    Thread.currentThread().setName(453        String.format("Forwarding %s on session %s to remote", driverCommand, sessionId));454    try {455      log(sessionId, command.getName(), command, When.BEFORE);456      response = executor.execute(command);457      //System.out.println("response ="+response.getValue());458      log(sessionId, command.getName(), command, When.AFTER);459      if (response == null) {460        return null;461      }462      // Unwrap the response value by converting any JSON objects of the form463      // {"ELEMENT": id} to RemoteWebElements.464      Object value = getElementConverter().apply(response.getValue());465      // :: Commented By Biswajit to Deserialize the response466      //response.setValue(value);467    } catch (WebDriverException e) {468      throw e;469    } catch (Exception e) {470      log(sessionId, command.getName(), command, When.EXCEPTION);471      String errorMessage = "Error communicating with the remote browser. " +472          "It may have died.";473      if (driverCommand.equals(DriverCommand.NEW_SESSION)) {474        errorMessage = "Could not start a new session. Possible causes are " +475            "invalid address of the remote server or browser start-up failure.";476      }477      UnreachableBrowserException ube = new UnreachableBrowserException(errorMessage, e);478      if (getSessionId() != null) {479        ube.addInfo(WebDriverException.SESSION_ID, getSessionId().toString());480      }481      if (getCapabilities() != null) {482        ube.addInfo("Capabilities", getCapabilities().toString());483      }484      throw ube;485    } finally {486      Thread.currentThread().setName(currentName);487    }488    try {489      errorHandler.throwIfResponseFailed(response, System.currentTimeMillis() - start);490    } catch (WebDriverException ex) {491      if (parameters != null && parameters.containsKey("using") && parameters.containsKey("value")) {492        ex.addInfo(493            "*** Element info",494            String.format(495                "{Using=%s, value=%s}",496                parameters.get("using"),497                parameters.get("value")));498      }499      ex.addInfo(WebDriverException.DRIVER_INFO, this.getClass().getName());500      if (getSessionId() != null) {501        ex.addInfo(WebDriverException.SESSION_ID, getSessionId().toString());502      }503      if (getCapabilities() != null) {504        ex.addInfo("Capabilities", getCapabilities().toString());505      }506      throw ex;507    }508    return response;509  }510  protected Response execute(String command) {511    return execute(command, ImmutableMap.of());512  }513  protected ExecuteMethod getExecuteMethod() {514    return executeMethod;515  }516  @Override517  public void perform(Collection<Sequence> actions) {518    execute(DriverCommand.ACTIONS, ImmutableMap.of("actions", actions));519  }520  @Override521  public void resetInputState() {522    execute(DriverCommand.CLEAR_ACTIONS_STATE);523  }524  public Keyboard getKeyboard() {525    return keyboard;526  }527  public Mouse getMouse() {528    return mouse;529  }530  /**531   * Override this to be notified at key points in the execution of a command.532   *533   * @param sessionId   the session id.534   * @param commandName the command that is being executed.535   * @param toLog       any data that might be interesting.536   * @param when        verb tense of "Execute" to prefix message537   */538  protected void log(SessionId sessionId, String commandName, Object toLog, When when) {539    if (!logger.isLoggable(level)) {540      return;541    }542    String text = String.valueOf(toLog);543    if (commandName.equals(DriverCommand.EXECUTE_SCRIPT)544        || commandName.equals(DriverCommand.EXECUTE_ASYNC_SCRIPT)) {545      if (text.length() > 100 && Boolean.getBoolean("webdriver.remote.shorten_log_messages")) {546        text = text.substring(0, 100) + "...";547      }548    }549    switch(when) {550      case BEFORE:551        logger.log(level, "Executing: " + commandName + " " + text);552        break;553      case AFTER:554        logger.log(level, "Executed: " + text);555        break;556      case EXCEPTION:557        logger.log(level, "Exception: " + text);558        break;559      default:560        logger.log(level, text);561        break;562    }563  }564  public FileDetector getFileDetector() {565    return fileDetector;566  }567  protected class RemoteWebDriverOptions implements Options {568    @Beta569    public Logs logs() {570      return remoteLogs;571    }572    public void addCookie(Cookie cookie) {573      cookie.validate();574      execute(DriverCommand.ADD_COOKIE, ImmutableMap.of("cookie", cookie));575    }576    public void deleteCookieNamed(String name) {577      execute(DriverCommand.DELETE_COOKIE, ImmutableMap.of("name", name));578    }579    public void deleteCookie(Cookie cookie) {580      deleteCookieNamed(cookie.getName());581    }582    public void deleteAllCookies() {583      execute(DriverCommand.DELETE_ALL_COOKIES);584    }585    @SuppressWarnings({"unchecked"})586    public Set<Cookie> getCookies() {587      Object returned = execute(DriverCommand.GET_ALL_COOKIES).getValue();588      Set<Cookie> toReturn = new HashSet<>();589      if (!(returned instanceof Collection)) {590        return toReturn;591      }592      ((Collection<?>) returned).stream()593          .map(o -> (Map<String, Object>) o)594          .map(rawCookie -> {595            Cookie.Builder builder =596                new Cookie.Builder((String) rawCookie.get("name"), (String) rawCookie.get("value"))597                    .path((String) rawCookie.get("path"))598                    .domain((String) rawCookie.get("domain"))599                    .isSecure(rawCookie.containsKey("secure") && (Boolean) rawCookie.get("secure"))600                    .isHttpOnly(601                        rawCookie.containsKey("httpOnly") && (Boolean) rawCookie.get("httpOnly"));602            Number expiryNum = (Number) rawCookie.get("expiry");603            builder.expiresOn(expiryNum == null ? null : new Date(SECONDS.toMillis(expiryNum.longValue())));604            return builder.build();605          })606          .forEach(toReturn::add);607      return toReturn;608    }609    public Cookie getCookieNamed(String name) {610      Set<Cookie> allCookies = getCookies();611      for (Cookie cookie : allCookies) {612        if (cookie.getName().equals(name)) {613          return cookie;614        }615      }616      return null;617    }618    public Timeouts timeouts() {619      return new RemoteTimeouts();620    }621    public ImeHandler ime() {622      return new RemoteInputMethodManager();623    }624    @Beta625    public Window window() {626      return new RemoteWindow();627    }628    protected class RemoteInputMethodManager implements WebDriver.ImeHandler {629      @SuppressWarnings("unchecked")630      public List<String> getAvailableEngines() {631        Response response = execute(DriverCommand.IME_GET_AVAILABLE_ENGINES);632        return (List<String>) response.getValue();633      }634      public String getActiveEngine() {635        Response response = execute(DriverCommand.IME_GET_ACTIVE_ENGINE);636        return (String) response.getValue();637      }638      public boolean isActivated() {639        Response response = execute(DriverCommand.IME_IS_ACTIVATED);640        return (Boolean) response.getValue();641      }642      public void deactivate() {643        execute(DriverCommand.IME_DEACTIVATE);644      }645      public void activateEngine(String engine) {646        execute(DriverCommand.IME_ACTIVATE_ENGINE, ImmutableMap.of("engine", engine));647      }648    } // RemoteInputMethodManager class649    protected class RemoteTimeouts implements Timeouts {650      public Timeouts implicitlyWait(long time, TimeUnit unit) {651        execute(DriverCommand.SET_TIMEOUT, ImmutableMap.of(652            "implicit", TimeUnit.MILLISECONDS.convert(time, unit)));653        return this;654      }655      public Timeouts setScriptTimeout(long time, TimeUnit unit) {656        execute(DriverCommand.SET_TIMEOUT, ImmutableMap.of(657            "script", TimeUnit.MILLISECONDS.convert(time, unit)));658        return this;659      }660      public Timeouts pageLoadTimeout(long time, TimeUnit unit) {661        execute(DriverCommand.SET_TIMEOUT, ImmutableMap.of(662            "pageLoad", TimeUnit.MILLISECONDS.convert(time, unit)));663        return this;664      }665    } // timeouts class.666    @Beta667    protected class RemoteWindow implements Window {668      public void setSize(Dimension targetSize) {669        execute(DriverCommand.SET_CURRENT_WINDOW_SIZE,670                ImmutableMap.of("width", targetSize.width, "height", targetSize.height));671      }672      public void setPosition(Point targetPosition) {673        execute(DriverCommand.SET_CURRENT_WINDOW_POSITION,674                ImmutableMap.of("x", targetPosition.x, "y", targetPosition.y));675      }676      @SuppressWarnings({"unchecked"})677      public Dimension getSize() {678        Response response = execute(DriverCommand.GET_CURRENT_WINDOW_SIZE);679        Map<String, Object> rawSize = (Map<String, Object>) response.getValue();680        int width = ((Number) rawSize.get("width")).intValue();681        int height = ((Number) rawSize.get("height")).intValue();682        return new Dimension(width, height);683      }684      Map<String, Object> rawPoint;685      @SuppressWarnings("unchecked")686      public Point getPosition() {687        Response response = execute(DriverCommand.GET_CURRENT_WINDOW_POSITION,688                                    ImmutableMap.of("windowHandle", "current"));689        rawPoint = (Map<String, Object>) response.getValue();690        int x = ((Number) rawPoint.get("x")).intValue();691        int y = ((Number) rawPoint.get("y")).intValue();692        return new Point(x, y);693      }694      public void maximize() {695        execute(DriverCommand.MAXIMIZE_CURRENT_WINDOW);696      }697      public void fullscreen() {698        execute(DriverCommand.FULLSCREEN_CURRENT_WINDOW);699      }700    }701  }702  private class RemoteNavigation implements Navigation {703    public void back() {704      execute(DriverCommand.GO_BACK);705    }706    public void forward() {707      execute(DriverCommand.GO_FORWARD);708    }709    public void to(String url) {710      get(url);711    }712    public void to(URL url) {713      get(String.valueOf(url));714    }715    public void refresh() {716      execute(DriverCommand.REFRESH);717    }718  }719  protected class RemoteTargetLocator implements TargetLocator {720    public WebDriver frame(int frameIndex) {721      execute(DriverCommand.SWITCH_TO_FRAME, ImmutableMap.of("id", frameIndex));722      return RemoteWebDriver.this;723    }724    public WebDriver frame(String frameName) {725      String name = frameName.replaceAll("(['\"\\\\#.:;,!?+<>=~*^$|%&@`{}\\-/\\[\\]\\(\\)])", "\\\\$1");726      List<WebElement> frameElements = RemoteWebDriver.this.findElements(727          By.cssSelector("frame[name='" + name + "'],iframe[name='" + name + "']"));728      if (frameElements.size() == 0) {729        frameElements = RemoteWebDriver.this.findElements(730            By.cssSelector("frame#" + name + ",iframe#" + name));731      }732      if (frameElements.size() == 0) {733        throw new NoSuchFrameException("No frame element found by name or id " + frameName);734      }735      return frame(frameElements.get(0));736    }737    public WebDriver frame(WebElement frameElement) {738      Object elementAsJson = new WebElementToJsonConverter().apply(frameElement);739      execute(DriverCommand.SWITCH_TO_FRAME, ImmutableMap.of("id", elementAsJson));740      return RemoteWebDriver.this;741    }742    public WebDriver parentFrame() {743      execute(DriverCommand.SWITCH_TO_PARENT_FRAME);744      return RemoteWebDriver.this;745    }746    public WebDriver window(String windowHandleOrName) {747      try {748        execute(DriverCommand.SWITCH_TO_WINDOW, ImmutableMap.of("handle", windowHandleOrName));749        return RemoteWebDriver.this;750      } catch (NoSuchWindowException nsw) {751        // simulate search by name752        String original = getWindowHandle();753        for (String handle : getWindowHandles()) {754          switchTo().window(handle);755          if (windowHandleOrName.equals(executeScript("return window.name"))) {756            return RemoteWebDriver.this; // found by name757          }758        }759        switchTo().window(original);760        throw nsw;761      }762    }763    public WebDriver defaultContent() {764      Map<String, Object> frameId = new HashMap<>();765      frameId.put("id", null);766      execute(DriverCommand.SWITCH_TO_FRAME, frameId);767      return RemoteWebDriver.this;768    }769    public WebElement activeElement() {770      Response response = execute(DriverCommand.GET_ACTIVE_ELEMENT);771      return (WebElement) response.getValue();772    }773    public Alert alert() {774      execute(DriverCommand.GET_ALERT_TEXT);775      return new RemoteAlert();776    }777  }778  private class RemoteAlert implements Alert {779    public RemoteAlert() {780    }781    public void dismiss() {782      execute(DriverCommand.DISMISS_ALERT);783    }784    public void accept() {785      execute(DriverCommand.ACCEPT_ALERT);786    }787    public String getText() {788      return (String) execute(DriverCommand.GET_ALERT_TEXT).getValue();789    }790    /**791     * @param keysToSend character sequence to send to the alert792     *793     * @throws IllegalArgumentException if keysToSend is null794     */795    public void sendKeys(String keysToSend) {796      if(keysToSend==null) {797        throw new IllegalArgumentException("Keys to send should be a not null CharSequence");798      }799      execute(DriverCommand.SET_ALERT_VALUE, ImmutableMap.of("text", keysToSend));800    }801  }802  public enum When {...Source:ChromeDriver.java  
...145    execute(GET, url);146  }147148  public String getCurrentUrl() {149    return execute(GET_CURRENT_URL).getValue().toString();150  }151152  public String getPageSource() {153    return execute(GET_PAGE_SOURCE).getValue().toString();154  }155156  public String getTitle() {157    return execute(GET_TITLE).getValue().toString();158  }159160  public String getWindowHandle() {161    return execute(GET_CURRENT_WINDOW_HANDLE).getValue().toString();162  }163164  public Set<String> getWindowHandles() {165    List<?> windowHandles = (List<?>)execute(GET_WINDOW_HANDLES).getValue();166    Set<String> setOfHandles = new HashSet<String>();167    for (Object windowHandle : windowHandles) {168      setOfHandles.add((String)windowHandle);169    }170    return setOfHandles;171  }172173  public Options manage() {174    return new ChromeOptions();175  }176177  public Navigation navigate() {178    return new ChromeNavigation();179  }180181  public void quit() {182    try {183      execute(QUIT);184    } finally {185      stopClient();186    }187  }188189  public TargetLocator switchTo() {190    return new ChromeTargetLocator();191  }192193  public Object executeScript(String script, Object... args) {194    ChromeResponse response;195    response = execute(EXECUTE_SCRIPT, script, args);196    if (response.getStatusCode() == -1) {197      return new ChromeWebElement(this, response.getValue().toString());198    } else {199      return response.getValue();200    }201  }202203  public boolean isJavascriptEnabled() {204    return true;205  }206207  public WebElement findElementById(String using) {208    return getElementFrom(execute(FIND_ELEMENT, "id", using));209  }210211  public List<WebElement> findElementsById(String using) {212    return getElementsFrom(execute(FIND_ELEMENTS, "id", using));213  }214215  public WebElement findElementByClassName(String using) {216    return getElementFrom(execute(FIND_ELEMENT, "class name", using));217  }218219  public List<WebElement> findElementsByClassName(String using) {220    return getElementsFrom(execute(FIND_ELEMENTS, "class name", using));221  }222223  public WebElement findElementByLinkText(String using) {224    return getElementFrom(execute(FIND_ELEMENT, "link text", using));225  }226227  public List<WebElement> findElementsByLinkText(String using) {228    return getElementsFrom(execute(FIND_ELEMENTS, "link text", using));229  }230231  public WebElement findElementByName(String using) {232    return getElementFrom(execute(FIND_ELEMENT, "name", using));233  }234235  public List<WebElement> findElementsByName(String using) {236    return getElementsFrom(execute(FIND_ELEMENTS, "name", using));237  }238239  public WebElement findElementByTagName(String using) {240    return getElementFrom(execute(FIND_ELEMENT, "tag name", using));241  }242243  public List<WebElement> findElementsByTagName(String using) {244    return getElementsFrom(execute(FIND_ELEMENTS, "tag name", using));245  }246247  public WebElement findElementByXPath(String using) {248    return getElementFrom(execute(FIND_ELEMENT, "xpath", using));249  }250251  public List<WebElement> findElementsByXPath(String using) {252    return getElementsFrom(execute(FIND_ELEMENTS, "xpath", using));253  }254255  public WebElement findElementByPartialLinkText(String using) {256    return getElementFrom(execute(FIND_ELEMENT, "partial link text", using));257  }258  259  public List<WebElement> findElementsByPartialLinkText(String using) {260    return getElementsFrom(execute(FIND_ELEMENTS, "partial link text", using));261  }262  263  public WebElement findElementByCssSelector(String using) {264    return getElementFrom(execute(FIND_ELEMENT, "css", using));265  }266267  public List<WebElement> findElementsByCssSelector(String using) {268    return getElementsFrom(execute(FIND_ELEMENTS, "css", using));269  }270  271  WebElement getElementFrom(ChromeResponse response) {272    Object result = response.getValue();273    List<?> elements = (List<?>)result;274    return new ChromeWebElement(this, (String)elements.get(0));275  }276277  List<WebElement> getElementsFrom(ChromeResponse response) {278    Object result = response.getValue();279    List<WebElement> elements = new ArrayList<WebElement>();280    for (Object element : (List<?>)result) {281      elements.add(new ChromeWebElement(this, (String)element));282    }283    return elements;284  }285  286  List<WebElement> findChildElements(ChromeWebElement parent, String by, String using) {287    return getElementsFrom(execute(FIND_CHILD_ELEMENTS, parent, by, using));288  }289290  public <X> X getScreenshotAs(OutputType<X> target) {291    return target.convertFromBase64Png(execute(SCREENSHOT).getValue().toString());292  }293  294  private class ChromeOptions implements Options {295296    public void addCookie(Cookie cookie) {297      execute(ADD_COOKIE, cookie);298    }299300    public void deleteAllCookies() {301      execute(DELETE_ALL_COOKIES);302    }303304    public void deleteCookie(Cookie cookie) {305      execute(DELETE_COOKIE, cookie.getName());306    }307308    public void deleteCookieNamed(String name) {309      execute(DELETE_COOKIE, name);310    }311312    public Set<Cookie> getCookies() {313      List<?> result = (List<?>)execute(GET_ALL_COOKIES).getValue();314      Set<Cookie> cookies = new HashSet<Cookie>();315      for (Object cookie : result) {316        cookies.add((Cookie)cookie);317      }318      return cookies;319    }320321    public Cookie getCookieNamed(String name) {322      return (Cookie)execute(GET_COOKIE, name).getValue();323    }324    325    public Speed getSpeed() {326      throw new UnsupportedOperationException("Not yet supported in Chrome");327    }328329    public void setSpeed(Speed speed) {330      throw new UnsupportedOperationException("Not yet supported in Chrome");331    }332  }333  334  private class ChromeNavigation implements Navigation {335    public void back() {336      execute(GO_BACK);
...Source:TestHelper.java  
...51        } 52        else 53        {54            Logging.info ("name: " + cookie.getName ());55            Logging.info ("value: " + cookie.getValue ());56            Logging.info ("domain: " + cookie.getDomain ());57            Logging.info ("path: " + cookie.getPath ());58            Logging.info ("expire: " + cookie.getExpiryDate ());59            Logging.info ("secure: " + cookie.isSecure ());60            Logging.info ("httpOnly: " + cookie.isPersistent ());61            Calendar expire = Calendar.getInstance ();62            expire.set (Calendar.YEAR, Calendar.getInstance ().get (Calendar.YEAR) + 2);63            // this is for Safari, domain=null and IE, secure=false64            org.openqa.selenium.Cookie sso = new org.openqa.selenium.Cookie (cookie.getName (),65                                                                             cookie.getValue (),66                                                                             APIEnvironment.domain,67                                                                             "/",68                                                                             expire.getTime (),69                                                                             false,70                                                                             false);71            return sso;72        }73    }74    public synchronized static List <org.openqa.selenium.Cookie> setAuthCookies (List <Cookie> cookies) 75    {76        List <org.openqa.selenium.Cookie> sso = new ArrayList <org.openqa.selenium.Cookie> ();77        if (cookies.size () == 0)78        {79            Logging.error ("getting no cookies");80        } 81        else82        {83            for (Cookie cookie : cookies)84                sso.add (setAuthCookie (cookie));85        }86        return sso;87    }88    89    public synchronized static void refreshCookies (List <org.openqa.selenium.Cookie> cookies) {90        try {91            List <Cookie> apacheCookies = new ArrayList <Cookie> ();92            for (org.openqa.selenium.Cookie cookie : cookies)93                if (!cookie.getName ().equals (ASID.name ()))94                    apacheCookies.add (new BasicClientCookie (cookie.getName (), cookie.getValue ()));95            String url = APIEnvironment.baseUrl + "/api/authentication-service/2/" + APIEnvironment.tenant + "/user/refresh";96            Map <String, Object> result = CareerHttpClient.post (url, "", apacheCookies);97            for (Auth auth : Auth.values ())98                if (result.get (auth.name ()) != null) {99                    Cookie apacheCookie = (Cookie) result.get (auth.name ());100                    Iterator <org.openqa.selenium.Cookie> i = cookies.iterator ();101                    while (i.hasNext ())102                        if (i.next ().getName ().equals (apacheCookie.getName ()))103                            i.remove ();104                    cookies.add (setAuthCookie (apacheCookie));105                }106        } catch (Exception e) {107            Logging.error (e.getMessage ());108        }...Source:Test.java  
...54		Set<org.openqa.selenium.Cookie> cookiesList1 =  driver.manage().getCookies();55		for(org.openqa.selenium.Cookie getcookies :cookiesList1) {56			System.out.print(getcookies.getName());57			System.out.println("");58		    System.out.println(getcookies.getValue());59		    System.out.println("");60		    System.out.println(getcookies.getDomain());61		    System.out.println("");62		    System.out.println(getcookies.getPath());63		    System.out.println("");64	}65		66		67		org.openqa.selenium.Cookie cookie1 = driver.manage().getCookieNamed("ACCOUNT_CHOOSER");68		Date Exp = cookie1.getExpiry();69		System.out.println(Exp);70		//Calendar cal = Calendar.getInstance();71		//cal.add(Calendar.DATE, -1);72		73		//driver.manage().deleteCookieNamed("ACCOUNT_CHOOSER");74		//driver.manage().deleteCookieNamed("GAPS");75		//driver.manage().deleteAllCookies();76		77		78		System.out.println("Deleted Cookies");79		System.out.println("");80		System.out.println("");81		System.out.println("");82		System.out.println("");83		Set<org.openqa.selenium.Cookie> cookiesList2 =  driver.manage().getCookies();84		for(org.openqa.selenium.Cookie getcookies :cookiesList2) {85		    System.out.println(getcookies);86		    System.out.println("");87		88		// TODO Auto-generated method stub8990	}91		driver.navigate().refresh();92		//driver.manage().addCookie((cookie1));93		//driver.manage().addCookie((org.openqa.selenium.Cookie) cookiesList1);94		Thread.sleep(5000);95		 for(org.openqa.selenium.Cookie cookie : allCookies) {96	            driver.manage().addCookie(cookie);97	            98		driver.navigate().refresh();99		driver.get("https://gmail.com/");100		101		System.out.println("Final Cookies");102		103		Set<org.openqa.selenium.Cookie> cookiesList3 =  driver.manage().getCookies();104		for(org.openqa.selenium.Cookie getcookies :cookiesList3) {105		    System.out.println(getcookies);106		    System.out.println("");107	}*/108109		110		File file = new File("Cookies.data");							111        try		112        {		113            // Delete old file if exists114			file.delete();		115            file.createNewFile();			116            FileWriter fileWrite = new FileWriter(file);							117            BufferedWriter Bwrite = new BufferedWriter(fileWrite);							118            // loop for getting the cookie information 		119            for(org.openqa.selenium.Cookie ck : driver.manage().getCookies())							120            {		121                Bwrite.write((ck.getName()+";"+ck.getValue()+";"+ck.getDomain()+";"+ck.getPath()+";"+ck.getExpiry()+";"+ck.isSecure()));																									122                Bwrite.newLine();			123        }		124            Bwrite.flush();			125            Bwrite.close();			126            fileWrite.close();			127        }catch(Exception ex)					128        {		129            ex.printStackTrace();			130        }		131		}132	}
...Source:WebDriver81CookiesTest.java  
...5960			Set<Cookie> cookies = driver.manage().getCookies();61			for(Cookie aCookie : cookies) {62				if(aCookie.getName().contentEquals("seleniumSimplifiedSearchNumVisits")) {63					assertEquals("This should be my first visit", "1", aCookie.getValue());64				}65			}	66		}67		68		@Test69		public void webDriverGetCookieDirectly() {7071			searchBox.clear();72			searchBox.sendKeys("Cookie Test");73			searchButton.click();7475			Cookie aCookie = driver.manage().getCookieNamed("seleniumSimplifiedSearchNumVisits");76			assertEquals("This should be my first visit", "1", aCookie.getValue());77		}78		79		@Test80		public void webDriverUpdateClonedCookie() {81			82			searchBox.clear();83			searchBox.sendKeys("Cookie Test");84			searchButton.click();85			86			refreshSearchPage();87			88			Cookie aCookie = driver.manage().getCookieNamed("seleniumSimplifiedSearchNumVisits");89			assertEquals("This should be my first visit", "1", aCookie.getValue());90			91			// Clone Cookie and set Value to what is wanted92			Cookie aNewCookie = new Cookie( aCookie.getName(),93					String.valueOf(42),94					aCookie.getDomain(),95					aCookie.getPath(),96					aCookie.getExpiry(),aCookie.isSecure());97			98			driver.manage().deleteCookie(aCookie);99			driver.manage().addCookie(aNewCookie);100			101			searchBox.clear();102			searchBox.sendKeys("New Cookie Test");103			searchButton.click();104			105			aCookie = driver.manage().getCookieNamed("seleniumSimplifiedSearchNumVisits");106			assertEquals("This should be my first visit", "43", aCookie.getValue());107			108		}109		110		@Test111		public void webDriverUpdateCookieBuilder() {112			113			searchBox.clear();114			searchBox.sendKeys("Cookie Test");115			searchButton.click();116			117			refreshSearchPage();118			119			Cookie aCookie = driver.manage().getCookieNamed("seleniumSimplifiedSearchNumVisits");120			assertEquals("This should be my first visit", "1", aCookie.getValue());121			122			// Clone Cookie and set Value to what is wanted123			Cookie aNewCookie = new Cookie.Builder( aCookie.getName(), String.valueOf(29))124					.domain(aCookie.getDomain())125					.path(aCookie.getPath())126					.expiresOn(aCookie.getExpiry())127					.isSecure(aCookie.isSecure()).build();128			129			driver.manage().deleteCookie(aCookie);130			driver.manage().addCookie(aNewCookie);131			132			searchBox.clear();133			searchBox.sendKeys("Another Cookie Test");134			searchButton.click();135			136			aCookie = driver.manage().getCookieNamed("seleniumSimplifiedSearchNumVisits");137			assertEquals("This should be my first visit", "30", aCookie.getValue());138			139		}140		141		@AfterClass142		public static void tearDown() {143			driver.quit();144		}145146}
...Source:BBWebdriverOptions.java  
...39            if (cookie.isHttpOnly()) {40                logger.warn("Cannot set httpOnly cookie using javascript.");41            }42            js.executeScript(cookie.isSecure() ?43                    "document.cookie = '" + cookie.getName() + "=" + cookie.getValue() + "; path=/; secure'" :44                    "document.cookie = '" + cookie.getName() + "=" + cookie.getValue() + "; path=/'");45            return;46        }47        delegate.addCookie(cookie);48    }49    @Override50    public void deleteCookieNamed(String name) {51        if (requiresJavaScript) {52            Cookie cookie = getCookieNamed(name);53            js.executeScript("document.cookie = '" + cookie.getName() + "=" + cookie.getValue() + "; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/'");54            return;55        }56        delegate.deleteCookieNamed(name);57    }58    @Override59    public void deleteCookie(Cookie cookie) {60        deleteCookieNamed(cookie.getName());61    }62    @Override63    public void deleteAllCookies() {64        getCookies().forEach(this::deleteCookie);65    }66    @Override67    public Set<Cookie> getCookies() {...Source:selenium.java  
...33		34		((JavascriptExecutor) driver).executeScript("document.cookie='ABTest_MiniCart=A_SHOW_MINICART'");35		/*36		Cookie cookie = driver.manage().getCookieNamed("ABTest_MiniCart");37		//System.out.println(driver.manage().getCookieNamed("ABTest_MiniCart").getValue());38		driver.manage().deleteCookie(cookie);39		//B_NO_MINICART40		System.out.println(cookie.getValue());41		driver.manage().addCookie(42		  new Cookie.Builder(cookie.getName(), "A_SHOW_MINICART")43		    .domain(cookie.getDomain())44		    .expiresOn(cookie.getExpiry())45		    .path(cookie.getPath())46		    .isSecure(cookie.isSecure())47		    .build()48		);49		50		*/51	}52}...Source:CookieTst.java  
...24        driver.findElement(By.cssSelector("input[name='btnG']")).click();25        wait.until(ExpectedConditions.presenceOfElementLocated(By.id("resultList")));26        //get number of times visited in cookie and assert = 127        Cookie aCookie = driver.manage().getCookieNamed("seleniumSimplifiedSearchNumVisits");28        assertEquals("1", aCookie.getValue());29        driver.quit();30    }31    @Test32    public void changeVisitValue (){33        String cookieName = "seleniumSimplifiedSearchNumVisits";34        Cookie newCookie;35        //delete original cookie36        driver.manage().deleteCookieNamed(cookieName);37        //set number of visits cookie in new cookie38        //build new cookie from values and change visits to 4239        newCookie = new Cookie(cookieName, "42");40        //check value41        assertEquals("42", newCookie.getValue());42        driver.quit();43    }44}...getValue
Using AI Code Generation
1import org.openqa.selenium.Cookie;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.firefox.FirefoxDriver;4public class CookieGetValue {5    public static void main(String[] args) {6        WebDriver driver = new FirefoxDriver();7        Cookie name = driver.manage().getCookieNamed("PREF");8        System.out.println(name.getValue());9        driver.quit();10    }11}getValue
Using AI Code Generation
1Cookie cookie = driver.manage().getCookieNamed("cookie_name");2String value = cookie.getValue();3Cookie cookie = new Cookie("cookie_name", "cookie_value");4driver.manage().addCookie(cookie);5Cookie cookie = driver.manage().getCookieNamed("cookie_name");6boolean isHttpOnly = cookie.isHttpOnly();7Cookie cookie = driver.manage().getCookieNamed("cookie_name");8boolean isSecure = cookie.isSecure();9Cookie cookie = driver.manage().getCookieNamed("cookie_name");10Date expiry = cookie.getExpiry();11Cookie cookie = driver.manage().getCookieNamed("cookie_name");12String domain = cookie.getDomain();13Cookie cookie = driver.manage().getCookieNamed("cookie_name");14String path = cookie.getPath();15Cookie cookie = driver.manage().getCookieNamed("cookie_name");16String name = cookie.getName();17Cookie cookie = driver.manage().getCookieNamed("cookie_name");18cookie.delete();19driver.manage().deleteAllCookies();20Set<Cookie> cookies = driver.manage().getCookies();21for(Cookie cookie : cookies) {22	System.out.println(cookie.getName() + " = " + cookie.getValue());23}24driver.manage().deleteCookieNamed("cookie_name");25Cookie cookie = driver.manage().getCookieNamed("cookie_name");26driver.manage().deleteCookie(cookie);27Cookie cookie = new Cookie("cookie_name", "cookie_value");28driver.manage().addCookie(cookie);29Cookie cookie = driver.manage().getCookieNamed("cookie_name");30System.out.println(cookie.getName() + " = " + cookiegetValue
Using AI Code Generation
1Cookie cookie = new Cookie.Builder("name", "value").domain("example.com").build();2driver.manage().addCookie(cookie);3String value = driver.manage().getCookieNamed("name").getValue();4driver.manage().addCookie(new Cookie("name", "value"));5String value = driver.manage().getCookieNamed("name").getValue();6driver.manage().addCookie(new Cookie("name", "value"));7Cookie cookie = driver.manage().getCookieNamed("name");8String value = cookie.getValue();9driver.manage().addCookie(new Cookie("name", "value"));10String value = driver.manage().getCookieNamed("name").getValue();11driver.manage().addCookie(new Cookie("name", "value"));12String value = driver.manage().getCookieNamed("name").getValue();13driver.manage().addCookie(new Cookie("name", "value"));14String value = driver.manage().getCookieNamed("name").getValue();15driver.manage().addCookie(new Cookie("name", "value"));16String value = driver.manage().getCookieNamed("name").getValue();17driver.manage().addCookie(new Cookie("name", "value"));18String value = driver.manage().getCookieNamed("name").getValue();19driver.manage().addCookie(new Cookie("name", "value"));20String value = driver.manage().getCookieNamed("name").getValue();21driver.manage().addCookie(new Cookie("name", "value"));22String value = driver.manage().getCookieNamedgetValue
Using AI Code Generation
1Cookie cookie = driver.manage().getCookieNamed("cookieName");2String cookieValue = cookie.getValue();3System.out.println("Cookie value is : " + cookieValue);4Cookie cookie = driver.manage().getCookieNamed("cookieName");5String cookieValue = cookie.getValue();6System.out.println("Cookie value is : " + cookieValue);7Cookie cookie = driver.manage().getCookieNamed("cookieName");8String cookieValue = cookie.getValue();9System.out.println("Cookie value is : " + cookieValue);10Cookie cookie = driver.manage().getCookieNamed("cookieName");11String cookieValue = cookie.getValue();12System.out.println("Cookie value is : " + cookieValue);13Cookie cookie = driver.manage().getCookieNamed("cookieName");14String cookieValue = cookie.getValue();15System.out.println("Cookie value is : " + cookieValue);16Cookie cookie = driver.manage().getCookieNamed("cookieName");17String cookieValue = cookie.getValue();18System.out.println("Cookie value is : " + cookieValue);19Cookie cookie = driver.manage().getCookieNamed("cookieName");20String cookieValue = cookie.getValue();21System.out.println("Cookie value is : " + cookieValue);22Cookie cookie = driver.manage().getCookieNamed("cookieName");23String cookieValue = cookie.getValue();24System.out.println("Cookie value is : " + cookieValue);25Cookie cookie = driver.manage().getCookieNamed("cookieName");26String cookieValue = cookie.getValue();27System.out.println("Cookie value is : " + cookieValue);28Cookie cookie = driver.manage().getCookieNamed("cookieName");29String cookieValue = cookie.getValue();30System.out.println("Cookie value is : " + cookieValue);31Cookie cookie = driver.manage().getCookieNamed("cookieName");32String cookieValue = cookie.getValue();33System.out.println("Cookie value is : " + cookieValue);getValue
Using AI Code Generation
1Cookie cookie = driver.manage().getCookieNamed("cookieName");2String cookieValue = cookie.getValue();3System.out.println(cookieValue);4Set<Cookie> allCookies = driver.manage().getCookies();5for(Cookie cookie : allCookies){6    System.out.println(cookie.getName() + " " + cookie.getValue());7}8driver.manage().deleteCookieNamed("cookieName");9driver.manage().deleteAllCookies();10driver.manage().addCookie(new Cookie("cookieName", "cookieValue"));11driver.manage().addCookie(new Cookie("cookieName", "cookieValue"));12driver.manage().addCookie(new Cookie("cookieName2", "cookieValue2"));13Set<Cookie> allCookies = driver.manage().getCookies();14boolean isCookiePresent = false;15for(Cookie cookie : allCookies){16    if(cookie.getName().equals("cookieName")){17        isCookiePresent = true;18        break;19    }20}21System.out.println(isCookiePresent);getValue
Using AI Code Generation
1System.out.println("Cookie value is: " + driver.manage().getCookieNamed("myCookie").getValue());2System.out.println("Cookie values are: " + driver.manage().getCookies());3driver.manage().deleteCookieNamed("myCookie");4driver.manage().deleteCookie(new Cookie("myCookie", "myCookieValue"));5driver.manage().deleteAllCookies();6driver.manage().addCookie(new Cookie("myCookie", "myCookieValue"));7driver.manage().deleteCookieNamed("myCookie");8driver.manage().deleteCookie(new Cookie("myCookie", "myCookieValue"));9driver.manage().deleteAllCookies();10driver.manage().addCookie(new Cookie("myCookie", "myCookieValue"));11driver.manage().deleteCookieNamed("myCookie");12driver.manage().deleteCookie(new Cookie("myCookie", "myCookieValue"));13driver.manage().deleteAllCookies();getValue
Using AI Code Generation
1WebDriver driver = new ChromeDriver();2Cookie cookie = driver.manage().getCookieNamed("NID");3String cookieValue = cookie.getValue();4System.out.println("Cookie value is: " + cookieValue);5driver.close();6driver.quit();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!!
