How to use toString method of org.openqa.selenium.Cookie class

Best Selenium code snippet using org.openqa.selenium.Cookie.toString

Source:RemoteWebDriver.java Github

copy

Full Screen

...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 {803 BEFORE,804 AFTER,805 EXCEPTION806 }807 @Override808 public String toString() {809 Capabilities caps = getCapabilities();810 if (caps == null) {811 return super.toString();812 }813 // w3c name first814 Object platform = caps.getCapability(PLATFORM_NAME);815 if (!(platform instanceof String)) {816 platform = caps.getCapability(PLATFORM);817 }818 if (platform == null) {819 platform = "unknown";820 }821 return String.format(822 "%s: %s on %s (%s)",823 getClass().getSimpleName(),824 caps.getBrowserName(),825 platform,...

Full Screen

Full Screen

Source:DriverUtil.java Github

copy

Full Screen

...32import org.openqa.selenium.remote.DesiredCapabilities;33import org.openqa.selenium.support.ui.ExpectedConditions;34import org.openqa.selenium.support.ui.WebDriverWait;35public class DriverUtil{36 public static String unicodetoString(String unicode){37 if(unicode==null||"".equals(unicode)){38 return null;39 }40 StringBuilder sb = new StringBuilder();41 int i = -1;42 int pos = 0;43 while((i=unicode.indexOf("\\u", pos)) != -1){44 sb.append(unicode.substring(pos, i));45 if(i+5 < unicode.length()){46 pos = i+6;47 sb.append((char)Integer.parseInt(unicode.substring(i+2, i+6), 16));48 }49 }50 return sb.toString();51 }52 private static void upLoadByCommonPost(String uploadUrl) throws IOException {53 String end = "\r\n";54 String twoHyphens = "--";55 String boundary = "******";56 URL url = new URL(uploadUrl);57 HttpURLConnection httpURLConnection = (HttpURLConnection) url58 .openConnection();59 httpURLConnection.setChunkedStreamingMode(128 * 1024);// 128K 应该按照文件大小来定义60 // 允许输入输出流61 httpURLConnection.setDoInput(true);62 httpURLConnection.setDoOutput(true);63 httpURLConnection.setUseCaches(false);64 // 使用POST方法65 httpURLConnection.setRequestMethod("POST");66 httpURLConnection.setRequestProperty("Connection", "Keep-Alive");67 httpURLConnection.setRequestProperty("Charset", "UTF-8");68 httpURLConnection.setRequestProperty("Content-Type",69 "multipart/form-data;boundary=" + boundary);70 DataOutputStream dos = new DataOutputStream(71 httpURLConnection.getOutputStream());72 dos.writeBytes(twoHyphens + boundary + end);73 dos.writeBytes("Content-Disposition: form-data; name=\"uploadfile\"; filename=\"1.jpg\";" + end);74 dos.writeBytes("Content-Type: image/jpeg" + end);75 dos.writeBytes(end);76 FileInputStream fis = new FileInputStream("d:\\test.jpg");77 byte[] buffer = new byte[1024*100]; // 100k78 int count = 0;79 // 读取文件80 while ((count = fis.read(buffer)) != -1) {81 dos.write(buffer, 0, count);82 }83 fis.close();84 dos.writeBytes(end);85 dos.writeBytes(twoHyphens + boundary + twoHyphens + end);86 dos.flush();87 InputStream is = httpURLConnection.getInputStream();88 InputStreamReader isr = new InputStreamReader(is, "utf-8");89 BufferedReader br = new BufferedReader(isr);90 String result;91 while ((result=br.readLine()) != null){92 System.out.println(result);93 }94 dos.close();95 is.close();96 }97 /**98 * WebDriver切换到当前页面99 */100 public static void switchToCurrentPage(WebDriver driver) {101 String handle = driver.getWindowHandle();102 for (String tempHandle : driver.getWindowHandles()) {103 if(!tempHandle.equals(handle)) {104 driver.switchTo().window(tempHandle);105 }106 }107 }108 /**109 * 切换frame110 * @param locator111 * @return 这个驱动程序切换到给定的frame112 */113 public static void switchToFrame(By locator,WebDriver driver) {114 driver.switchTo().frame(driver.findElement(locator));115 }116 117 /**118 * 判断是否有弹窗,如有弹窗则返回弹窗内的text,否则返回空119 */120 public static String alertFlag(WebDriver driver){121 String str = "";122 try {123 Alert alt = driver.switchTo().alert();124 str = alt.getText();125 System.out.println(str);126 alt.accept();127 128 } catch (Exception e) {129 //不做任何处理130 }131 return str;132 }133 134 135 136 /**137 * 关闭所有进程(针对64位的),仅支持同步138 * @param driver139 * @throws IOException 140 */141 public static void close(WebDriver driver,String exec) throws IOException{142 if(driver != null){143 driver.close();144 Runtime.getRuntime().exec(exec);145 }146 }147 148 149 /**150 * 关闭所有进程(针对32位的)151 * @param driver152 */153 public static void close(WebDriver driver){154 if(driver != null){155 driver.quit();156 }157 }158 159 160 /**161 * 162 * @param type ie 或 chrome163 * @return164 */165 public static WebDriver getDriverInstance(String type){166 WebDriver driver = null;167 if(type.equals("ie")){168 System.setProperty("webdriver.ie.driver", "C:/ie/IEDriverServer.exe");169 DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();170 ieCapabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);171 ieCapabilities.setCapability(InternetExplorerDriver.BROWSER_ATTACH_TIMEOUT,15000);172 driver = new InternetExplorerDriver(ieCapabilities);173 driver.manage().window().maximize();174 }175 if (type.equals("chrome")){176 ChromeOptions options = new ChromeOptions();177 options.addArguments("disable-infobars");// 设置chrome浏览器的参数,使其不弹框提示(chrome正在受自动测试软件的控制)178 options.setBinary("C:/Users/Administrator/AppData/Local/Google/Chrome/Application/chrome.exe");179 System.setProperty("webdriver.chrome.driver", "C:/chrome/chromedriver.exe");180 driver = new ChromeDriver(options);181 driver.manage().window().maximize();182 }183 return driver;184 }185 /**186 * 使用代理ip187 * @param type ie 或 chrome188 * @return189 */190 public static WebDriver getDriverInstance(String type,String ip,int port){191 WebDriver driver = null;192 if(type.equals("ie")){193 System.setProperty("webdriver.ie.driver", "C:/ie/IEDriverServer.exe");194 195 String proxyIpAndPort = ip+ ":" + port;196 Proxy proxy=new Proxy();197 proxy.setHttpProxy(proxyIpAndPort).setFtpProxy(proxyIpAndPort).setSslProxy(proxyIpAndPort);198 199 DesiredCapabilities cap = DesiredCapabilities.internetExplorer();200 //代理201 cap.setCapability(CapabilityType.ForSeleniumServer.AVOIDING_PROXY, true);202 cap.setCapability(CapabilityType.ForSeleniumServer.ONLY_PROXYING_SELENIUM_TRAFFIC, true);203 System.setProperty("http.nonProxyHosts", ip);204 cap.setCapability(CapabilityType.PROXY, proxy);205 206 cap.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);207 cap.setCapability(InternetExplorerDriver.BROWSER_ATTACH_TIMEOUT,15000);208 driver = new InternetExplorerDriver(cap);209 driver.manage().window().maximize();210 }211 return driver;212 }213 214 215 /**216 * 获取cookie217 * @param driver218 * @return219 */220 public static String getCookie(WebDriver driver) {221 //获得cookie用于发包222 Set<org.openqa.selenium.Cookie> cookies = driver.manage().getCookies(); 223 StringBuffer tmpcookies = new StringBuffer();224 for (org.openqa.selenium.Cookie cookie : cookies) {225 String name = cookie.getName();226 String value = cookie.getValue();227 tmpcookies.append(name + "="+ value + ";");228 }229 String str = tmpcookies.toString();230 if(!str.isEmpty()){231 str = str.substring(0,str.lastIndexOf(";"));232 }233 return str; 234 }235 236 /**237 * 获取cookie238 * @param driver239 * @param jsession240 * @return241 */242 public static String getCookie(WebDriver driver,String jsession) {243 //获得cookie用于发包244 Set<org.openqa.selenium.Cookie> cookies = driver.manage().getCookies(); 245 StringBuffer tmpcookies = new StringBuffer();246 247 for (org.openqa.selenium.Cookie cookie : cookies) {248 String name = cookie.getName();249 String value = cookie.getValue();250 tmpcookies.append(name + "="+ value + ";");251 }252 tmpcookies.append("JSESSIONID");253 tmpcookies.append("=");254 tmpcookies.append(jsession);255 String str = tmpcookies.toString();256 return str; 257 }258 /**259 * 获取cookie 招商260 * @param driver261 * @return262 */263 public static String getCookieCmd(WebDriver driver) {264 //获得cookie用于发包265 Set<org.openqa.selenium.Cookie> cookies = driver.manage().getCookies();266 StringBuffer tmpcookies = new StringBuffer();267 for (org.openqa.selenium.Cookie cookie : cookies) {268 String name = cookie.getName();269 String value = cookie.getValue();270 if (name.equals("ProVersion")){271 tmpcookies.append(name + "=;");272 }else {273 tmpcookies.append(name + "="+ value + ";");274 }275 }276 String str = tmpcookies.toString();277 if(!str.isEmpty()){278 str = str.substring(0,str.lastIndexOf(";"));279 }280 return str;281 }282 /**283 * 根据节点位置,对节点进行裁剪,获得截图284 * @param driver285 * @param webElement286 * @return287 * @throws IOException288 */289 public static BufferedImage createElementImage(WebDriver driver, WebElement webElement) throws IOException {290 // 获得webElement的位置和大小。291 Point location = webElement.getLocation();292 Dimension size = webElement.getSize();293 // 创建全屏截图。294 BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(takeScreenshot(driver)));295 // 截取webElement所在位置的子图。296 BufferedImage croppedImage = originalImage.getSubimage(location.getX(), location.getY(), size.getWidth(),size.getHeight());297 return croppedImage;298 }299 /**300 * 保存截图文件301 * @param bi302 * @throws IOException303 */304 public static void writeImageFile(BufferedImage bi,String imgPath) throws IOException {305 File outputfile = new File(imgPath);306 ImageIO.write(bi, "jpg", outputfile);307 }308// public StringBuffer connection(Map<String,String> map, String strURL) {309// // start310// HttpClient httpClient = new HttpClient();311//312// httpClient.getHostConfiguration().setProxy("10.192.10.101", 8080); //313// httpClient.getParams().setAuthenticationPreemptive(true);314//315// HttpConnectionManagerParams managerParams = httpClient316// .getHttpConnectionManager().getParams();317// // 设置连接超时时间(单位毫秒)318// managerParams.setConnectionTimeout(30000);319// // 设置读数据超时时间(单位毫秒)320// managerParams.setSoTimeout(120000);321//322// PostMethod postMethod = new PostMethod(strURL);323// // 将请求参数XML的值放入postMethod中324// String strResponse = null;325// StringBuffer buffer = new StringBuffer();326// // end327// try {328// //设置参数到请求对象中,重点是map中有几个参数NameValuePair数组也必须设置成几,不然329// //会空指针异常330// NameValuePair[] nvps = new NameValuePair[4];331// int index = 0;332// for(String key : map.keySet()){333// nvps[index++]=new NameValuePair(key, map.get(key));334// }335// postMethod.setRequestBody(nvps);336// int statusCode = httpClient.executeMethod(postMethod);337// if (statusCode != HttpStatus.SC_OK) {338// throw new IllegalStateException("Method failed: "339// + postMethod.getStatusLine());340// }341// BufferedReader reader = null;342// reader = new BufferedReader(new InputStreamReader(343// postMethod.getResponseBodyAsStream(), "UTF-8"));344// while ((strResponse = reader.readLine()) != null) {345// buffer.append(strResponse);346// }347// } catch (Exception ex) {348// throw new IllegalStateException(ex.toString());349// } finally {350// // 释放连接351// postMethod.releaseConnection();352// }353// return buffer;354// }355 public static byte[] takeScreenshot(WebDriver driver) throws IOException {356 TakesScreenshot takesScreenshot = (TakesScreenshot) driver;357 return takesScreenshot.getScreenshotAs(OutputType.BYTES);358 }359 /**360 * 根据传入包名 在templates包下创建此包,并返回该路径361 * @param packageName362 * @return...

Full Screen

Full Screen

Source:SeleniumBot1.java Github

copy

Full Screen

...78 //webDriver = new ChromeDriver(cds,options);79 //webWait= new WebDriverWait(webDriver,var1);80 }81 catch(WebDriverException| ArrayIndexOutOfBoundsException e){82 System.out.println(e.toString());83 System.out.println(e.getMessage());84 }85} 86 @Override87 public void run(){88 webDriver = new ChromeDriver(cds,options);89 webWait= new WebDriverWait(webDriver,var1);90 String rand1=null;91 String rand2=null;92 //SeleniumBot1 driver = this ;93 //File baseDirectory=new File("SeleniumBot.java");94 Logger logger1=Logger.getLogger(SeleniumBot1.class.getName());95 try{96 System.setProperty("webdriver.chrome.driver","C:/Users/PAUL/Documents/AAAfiles/c++/SeleniumBot/chromedriver_win32/chromedriver.exe");97 webDriver.navigate().to("https://tuckercraig.com/dino/");98 rand1=webDriver.getCurrentUrl();99 log(rand1);100 rand2=webDriver.getTitle();101 log(rand2);102 WebElement body = webDriver.findElement(By.cssSelector("body"));103 webDriver.manage().window().setPosition(new Point(-10,0));104 webDriver.manage().window().setSize(new Dimension(715,780));105 body.click();106 body.sendKeys(" ");107 body.sendKeys(" ");108 System.out.println(webDriver.manage().getCookies().toArray(new Cookie[0])[0].getName());109 System.out.println(Arrays.deepToString(webDriver.manage().getCookies().toArray(new Cookie[0])));110 Cookie cookie = new Cookie.Builder111 ("This is random","Random")112 .build();113 webDriver.manage().addCookie(cookie);114 System.out.println(Arrays.deepToString(webDriver.manage().getCookies().toArray(new Cookie[0])));115 //System.out.println(Arrays.deepToString(webDriver.manage().logs().getAvailableLogTypes().toArray(new LocalLogs[0])));116 while(true){117 try{118 Thread.sleep(80000);119 webDriver.navigate().refresh();120 Thread.sleep(2500);121 webDriver.findElement(By.cssSelector("body")).sendKeys(" ");122 Thread.sleep(80000);123 webDriver.findElement(By.xpath("/html/body/footer/ul/li[1]/a")).click();124 Thread.sleep(2500);125 webDriver.findElement(By.cssSelector("body")).sendKeys(" ");126 }127 catch(InterruptedException E){128 E.getMessage();129 }130 }131 }132 catch(ElementNotInteractableException|NoSuchElementException|133 InvalidArgumentException |TimeoutException e){ 134 logger1.log(Level.SEVERE,e.toString());135 } 136 }137 public static synchronized void impose(Thread T1,int priority,String var1){138 T1.setPriority(priority);139 T1.setName(var1);140 T1.start();141 System.out.println("Thread " + T1.getName() + " is running");142 }143 public void log(WebElement webElement){144 this.logger.log(Level.INFO, webElement.toString());145 }146 public void log(String webElement){147 this.logger.log(Level.INFO, webElement.toString());148 }149 public static void main(String[] args){150 try{151 //while(true){152 Thread Thread1 = new SeleniumBot1(8); 153 Thread Thread2= new ChromeBot1();154 SeleniumBot1.impose(Thread1,8,"SeleniumBot");155 Thread.sleep(40000);156 SeleniumBot1.impose(Thread2,6,"ChromeBot");157 }158 catch(InterruptedException E){159 E.printStackTrace();160 } 161 } ...

Full Screen

Full Screen

Source:session_webdriver.java Github

copy

Full Screen

...107// 108// Capabilities cap = ((RemoteWebDriver)driver).getCapabilities();109// SessionId session= ((RemoteWebDriver)driver).getSessionId();110// 111// System.out.println("Session id: " + session.toString());112// System.out.println("command_exe: " + ce.toString());113// WebDriver driver1 = WebDriver.Remote(command_executor=url,desired_capabilities={})114 115// DesiredCapabilities capabilities = DesiredCapabilities.chrome();116// WebDriver driver1 = new RemoteWebDriver(new URL("http://localhost:4722/wd/hub"), capabilities);117//118// SessionId ses= ((RemoteWebDriver)driver1).getSessionId();119// System.out.println("Session id: " + ses.toString());120 121// HttpCommandExecutor executor = (HttpCommandExecutor) ((RemoteWebDriver) driver).getCommandExecutor();122// URL url = executor.getAddressOfRemoteServer();123// SessionId session_id = ((RemoteWebDriver) driver).getSessionId();124// System.out.println(url);125// System.out.println(session_id );126// RemoteWebDriver driver2 = createDriverFromSession(session_id, url);127// driver2.get("https://www.amazon.in/?ref_=nav_signin&");128 }129} ...

Full Screen

Full Screen

Source:BasePageObject.java Github

copy

Full Screen

...59 return driver.switchTo().alert();60 }61 protected void SwitchToNewWindow(String expectedTitle) {62 63// String window =driver.getWindowHandles().iterator().next().toString();64// driver.switchTo().window(window);65// String firstWindow = driver.getWindowHandle();66//67// Set<String> allWindows = driver.getWindowHandles();68// for(String firstWindow1 : allWindows) {69// 70// }71 String firstWindow = driver.getWindowHandle();72 Set<String> allWindows = driver.getWindowHandles();73 Iterator<String> windowsIterator = allWindows.iterator();74 while (windowsIterator.hasNext()) {75 String windowHandle = windowsIterator.next().toString();76 if (!windowHandle.equals(firstWindow)) {77 driver.switchTo().window(windowHandle);78 if (getCurrentPageTitle().equals(expectedTitle)) {79 break;80 }81 }82 }83 }84 public void switchToWindowWithTitle(String expectedTitle) {85 // Switching to new window86 String firstWindow = driver.getWindowHandle();87 Set<String> allWindows = driver.getWindowHandles();88 Iterator<String> windowsIterator = allWindows.iterator();89 while (windowsIterator.hasNext()) {90 String windowHandle = windowsIterator.next().toString();91 if (!windowHandle.equals(firstWindow)) {92 driver.switchTo().window(windowHandle);93 if (getCurrentPageTitle().equals(expectedTitle)) {94 break;95 }96 }97 }98 }99 protected void switchToFrame(By frameLocator) {100 WebElement frame = find(frameLocator);101 driver.switchTo().frame(frame);102 }103 104 ...

Full Screen

Full Screen

Source:searchTest.java Github

copy

Full Screen

...48 List<HashMap<String, Object>> cookies = objectMapper.readValue(new File("cookies.yaml"), typeReference);49 System.out.println(cookies);50 //driver添加cookie51 cookies.forEach(cookie -> {52 webDriver.manage().addCookie(new Cookie(cookie.get("name").toString(), cookie.get("value").toString()));53 }54 );55 webDriver.navigate().refresh();56 }57}...

Full Screen

Full Screen

Source:SeleniumExample2.java Github

copy

Full Screen

...25 System.out.println(login);26 login.click();27 Thread.sleep(3000);28 WebElement username = driver.findElement(By.id("TPL_username_1"));29 System.out.println(username.toString());30 username.sendKeys(user);31 Thread.sleep(3000);32 WebElement password = driver.findElement(By.id("TPL_password_1"));33 System.out.println(password.toString());34 password.sendKeys(pass);35 Thread.sleep(3000);36 driver.findElement(By.cssSelector("button#J_SubmitStatic.J_Submit")).click();37 Thread.sleep(3000);38 //System.out.println(driver.getPageSource());39 Set<Cookie> cookieSet = driver.manage().getCookies();40 for(Cookie cookie:cookieSet){41 System.out.println(cookie.getName()+"="+cookie.getValue());42 }43 //driver.close();44 }45}...

Full Screen

Full Screen

Source:BatchRunner.java Github

copy

Full Screen

...17 18 DesiredCapabilities capabilities = DesiredCapabilities.chrome();19 System.setProperty("webdriver.chrome.driver", "D:\\GSTNAutomationFramework\\GSTN\\drivers\\chromedriver.exe");20 WebDriver driver = new ChromeDriver();21 System.out.println(driver.toString());22 driver.get("http://localhost:2010/homepage");23 Thread.sleep(4000);24 Set<Cookie> allCookies = driver.manage().getCookies();25 System.out.println("Coockies111 = "+allCookies);26 driver.close();27 Thread.sleep(4000);28 WebDriver driver2=new ChromeDriver();29 driver2.get("http://localhost:2010/homepage");30 for(Cookie cookie : allCookies)31 {32 driver2.manage().addCookie(cookie);33 }34 System.out.println(driver2.toString());35 driver2.get("http://localhost:2010/homepage");36 Set<Cookie> allCookies1 = driver.manage().getCookies();37 System.out.println("Coockies222 = "+allCookies1);38 }39}...

Full Screen

Full Screen

toString

Using AI Code Generation

copy

Full Screen

1Cookie cookie = driver.manage().getCookieNamed("cookieName");2String cookieValue = cookie.toString().split("value=")[1].split(";")[0];3System.out.println(cookieValue);4Cookie cookie = driver.manage().getCookieNamed("cookieName");5String cookieValue = cookie.getValue();6System.out.println(cookieValue);7String cookieValue = driver.manage().getCookieNamed("cookieName").getValue();8System.out.println(cookieValue);9String cookieValue = driver.manage().getCookieNamed("cookieName").toString().split("value=")[1].split(";")[0];10System.out.println(cookieValue);11String cookieValue = driver.manage().getCookieNamed("cookieName").toString().split("value=")[1].split(";")[0];12System.out.println(cookieValue);13String cookieValue = driver.manage().getCookieNamed("cookieName").toString().split("value=")[1].split(";")[0];14System.out.println(cookieValue);15String cookieValue = driver.manage().getCookieNamed("cookieName").toString().split("value=")[1].split(";")[0];16System.out.println(cookieValue);17String cookieValue = driver.manage().getCookieNamed("cookieName").toString().split("value=")[1].split(";")[0];18System.out.println(cookieValue);19String cookieValue = driver.manage().getCookieNamed("cookieName").toString().split("value=")[1].split(";")[0];20System.out.println(cookieValue);21String cookieValue = driver.manage().get

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful