How to use length method of org.openqa.selenium.Enum Keys class

Best Selenium code snippet using org.openqa.selenium.Enum Keys.length

Source:CommonLibrary.java Github

copy

Full Screen

...336 public void deleteSheet() throws Exception {337 String oldsheet = HttpLibrary.sheetName();338 System.out.println("Deleting sheet named : " + oldsheet);339 /*340 * if(oldsheet.split("\\,").length > 1){ String [] s =341 * oldsheet.split("\\,"); for(int j=0;j<s.length-1;j++){342 * HttpLibrary.restDelete(getAccessToken(), s[j]);}343 * 344 * 345 * }346 */347 sheet = HttpLibrary.addSheet();348 Thread.sleep(2000);349 System.out.println("added new sheet named : " + sheet);350 HttpLibrary.restDelete(getAccessToken(), oldsheet);351 HttpLibrary.sheetName();352 setSheet(sheet);353 }354 public void loadTemplate(String name) throws InterruptedException {355 Thread.sleep(1000);356 driver.findElement(By.cssSelector("input[ng-model='searchString']"))357 .sendKeys(name);358 Thread.sleep(1000);359 List<WebElement> Template_List = driver.findElements(By360 .cssSelector("div.section ul li"));361 for (WebElement we : Template_List) {362 // System.out.println(we.getText());363 if (we.getText().contains(name)) {364 System.out.println("Clicking on " + we.getText());365 Thread.sleep(1500);366 we.findElement(By.cssSelector("a[title='Load template']"))367 .click();368 break;369 }370 }371 Thread.sleep(2000);372 driver.findElement(373 By.cssSelector("div#confirmationPopup button#accept")).click();374 Thread.sleep(1000);375 }376 // replace [ , ] , " , " characters in string377 public static String remSpecialCharacters(String temp) {378 try {379 temp = temp.replace("[", "");380 temp = temp.replace("]", "");381 temp = temp.replace("\"", "");382 } catch (java.lang.NullPointerException e) {383 }384 return temp;385 }386 public String appendIdToUpdateTemplateValues(String idata, int id) {387 int dot1 = idata.indexOf(",");388 int dot2 = idata.indexOf(",", dot1 + 1);389 // System.out.println(dot1 + " : " + dot2);390 String substr = "," + id + ","391 + idata.substring(dot2 + 1, idata.length());392 return substr;393 }394 public void insertDataIntoTemplate(String data) throws InterruptedException {395 Keyboard press = ((HasInputDevices) driver).getKeyboard();396 Thread.sleep(200);397 System.out.println("Inserting data into Template");398 String[] col_data = data.split("\\,");399 // inserting data in contact template400 // press.pressKey(Keys.TAB);401 for (int i = 0; i < col_data.length; i++) {402 if (i != 0) {403 press.pressKey(Keys.TAB);404 }405 press.pressKey(col_data[i]);406 // System.out.println(col_data[i]);407 Thread.sleep(1300);408 }409 }410 public static String generateJaywayQueryString(int i, String[] data,411 String type) {412 String query = "";413 // System.out.println("type: " + type);414 for (int k = 2; k < data.length; k++) {415 if (k == data.length - 1) {416 if (type.equals("enum"))417 query += ".." + data[k];418 else419 query += "." + data[k];420 } else {421 if (k == 2) {422 query += ".." + data[k] + "[" + i + "]";423 } else {424 query += ".." + data[k];425 }426 }427 }428 // System.out.println(query);429 return query;430 }431 public void clickOn(App on) throws InterruptedException, IOException {432 try {433 Thread.sleep(1500);434 List<WebElement> appMenu = driver.findElements(By435 .cssSelector("div.menuContent ul li"));436 List<WebElement> middleButtons = driver.findElements(By437 .cssSelector("div.msgBox"));438 List<WebElement> checkboxes = driver.findElements(By439 .cssSelector("div.checkbox"));440 switch (on) {441 case InsertAllRows:442 appMenu.get(1).click();443 Thread.sleep(500);444 System.out.println("insert checkbox selected ? "445 + checkboxes.get(2).isSelected());446 if (!checkboxes.get(2).isSelected()) {447 checkboxes.get(2).click();448 } else {449 System.out.println("already checkbox is checked");450 }451 middleButtons.get(1)452 .findElement(By.cssSelector("div.button-box a"))453 .click();454 break;455 case DeleteAllRows:456 appMenu.get(2).click();457 Thread.sleep(500);458 if (!checkboxes.get(3).isSelected()) {459 checkboxes.get(3).click();460 } else {461 System.out.println("already checkbox is checked");462 }463 middleButtons.get(2)464 .findElement(By.cssSelector("div.button-box a"))465 .click();466 break;467 case RefreshSelectedRows:468 appMenu.get(3).click();469 Thread.sleep(1000);470 if (checkboxes.get(4).isSelected()) {471 checkboxes.get(4).click();472 } else {473 System.out.println("already checkbox is unchecked");474 }475 middleButtons.get(3)476 .findElement(By.cssSelector("div.button-box a"))477 .click();478 Thread.sleep(1500);479 break;480 case DownloadWithFilter:481 appMenu.get(0).click();482 Thread.sleep(500);483 if (!checkboxes.get(1).isSelected()) {484 checkboxes.get(1).click();485 } else {486 System.out.println("already checkbox is checked");487 }488 middleButtons.get(0)489 .findElement(By.cssSelector("div.button-box a"))490 .click();491 break;492 case InsertSelectedRows:493 appMenu.get(1).click();494 Thread.sleep(1000);495 if (checkboxes.get(2).isSelected()) {496 checkboxes.get(2).click();497 } else {498 System.out.println("already checkbox is unchecked");499 }500 middleButtons.get(1)501 .findElement(By.cssSelector("div.button-box a"))502 .click();503 break;504 case DeleteSelectedRows:505 appMenu.get(2).click();506 Thread.sleep(1000);507 if (checkboxes.get(3).isSelected()) {508 checkboxes.get(3).click();509 } else {510 System.out.println("already checkbox is unchecked");511 }512 middleButtons.get(2)513 .findElement(By.cssSelector("div.button-box a"))514 .click();515 break;516 case RefreshAllRows:517 appMenu.get(3).click();518 Thread.sleep(1000);519 if (!checkboxes.get(4).isSelected()) {520 checkboxes.get(4).click();521 } else {522 System.out.println("already checkbox is checked");523 }524 middleButtons.get(3)525 .findElement(By.cssSelector("div.button-box a"))526 .click();527 break;528 case DownloadWithoutFilter:529 appMenu.get(0).click();530 Thread.sleep(1000);531 if (checkboxes.get(1).isSelected()) {532 checkboxes.get(1).click();533 } else {534 System.out.println("already checkbox is unchecked");535 }536 middleButtons.get(0)537 .findElement(By.cssSelector("div.button-box a"))538 .click();539 break;540 default:541 System.out.println("Invalid input");542 }543 } catch (org.openqa.selenium.WebDriverException e) {544 Files.write(Paths.get("D://error.txt"), driver.getPageSource()545 .getBytes());546 clickOn(on);547 // Assert.fail("Unable to click on Data Operation page");548 }549 }550 public String getNotification() throws InterruptedException {551 int Time = 0;552 String notification = "";553 do {554 Time += 1;555 try {556 WebElement notify = driver.findElement(By557 .cssSelector("div.notifyjs-container span"));558 if (notify.isDisplayed()) {559 notification = notify.getText();560 if (notification.equals("")) {561 notify = driver.findElement(By562 .cssSelector("div.notifyjs-container span"));563 System.out.println("trying to get notification again");564 }565 Thread.sleep(1000);566 break;567 }568 } catch (Exception e) {569 System.out.println("not visible");570 Thread.sleep(20);571 }572 } while (Time < 20);573 return notification;574 }575 public String tableId() throws Exception {576 setAccessToken(HttpLibrary.getAccessTokenRestApi());577 String tableId = HttpLibrary.getTableId(workbookId, getAccessToken());578 System.out.println(tableId);579 return tableId;580 }581 @SuppressWarnings("rawtypes")582 public static ArrayList<String> templateHeader(583 HashMap<String, String> header) {584 // Getting header row text585 ArrayList<String> head = new ArrayList<String>();586 Set set = header.entrySet();587 Iterator i = set.iterator();588 while (i.hasNext()) {589 Map.Entry me = (Map.Entry) i.next();590 head.add((String) me.getKey());591 }592 return head;593 }594 public void waitUntilLoadingEnds() throws InterruptedException {595 try {596 WebElement loading = driver.findElement(By597 .cssSelector("div#loadingDiv"));598 System.out.println(loading.getAttribute("aria-hidden"));599 while (loading.getAttribute("aria-hidden").equals("false")) {600 loading = driver.findElement(By.cssSelector("div#loadingDiv"));601 }602 } catch (NoSuchElementException e) {603 System.out.println("no loading");604 }605 }606 public static String capture(WebDriver driver, String screenShotName)607 throws IOException {608 TakesScreenshot ts = (TakesScreenshot) driver;609 File source = ts.getScreenshotAs(OutputType.FILE);610 String dest = System.getProperty("user.dir") + "\\ErrorScreenshots\\"611 + screenShotName + ".png";612 File destination = new File(dest);613 FileUtils.copyFile(source, destination);614 return dest;615 }616 public org.json.JSONObject getRowsData(boolean allRows, ExtentTest logger)617 throws Exception {618 System.out.println("Waiting for Excel sheet to get latest data");619 // keep this when updating something from SC App620 Thread.sleep(22000);621 HashMap<String, String> header = getHeader();622 ArrayList<String> head = templateHeader(getHeader());623 List<String> rows = new ArrayList<String>();624 String rowData = null;625 if (allRows) {626 for (int i = 0; i < CommonLibrary.getTotalRows(); i++) {627 // System.out.println("*************");628 rowData = getRows(header, head, i);629 if (rowData.equals("")) {630 System.out.println("found only this rows breaking loop"631 + rowData);632 break;633 }634 System.out635 .println("Printing row before adding to list at index ["636 + i + "]\n" + rowData);637 String[] values = rowData.split("\\,");638 try {639 if (!values[1].equals("")) {640 rows.add(rowData);641 successfullRows.add(remSpecialCharacters(values[1])642 .trim());643 // System.out.println("row " + i + " added");644 } else if (!values[0].equals("")) {645 errorRows.put(rowData, i);646 }647 } catch (ArrayIndexOutOfBoundsException e) {648 break;649 }650 }651 } else {652 String id = "";653 for (int i = 0;; i++) {654 rowData = getRows(header, head, i);655 String[] values = rowData.split("\\,");656 try {657 // if (!values[1].equals("")) {658 if (values[0].equals("")) {659 if (id.equals("")) {660 System.out661 .println("setting id value to check multiple line if present");662 id = values[1];663 System.out.println(id);664 // rows.add(rowData);665 }666 if (values[1].equals(id)) {667 rows.add(rowData);668 } else {669 System.out670 .println("breaking for loop as no more ids matched with same id");671 break;672 }673 }674 } catch (java.lang.ArrayIndexOutOfBoundsException e) {675 // System.out.println(e);676 break;677 }678 }679 }680 System.out.println("List :\n" + rows);681 org.json.JSONObject fromExcel = null;682 // if (head.size() == rowData.length()) {683 // need to send multiple rows (record with multiple sublist)684 // rows.add(rowData);685 fromExcel = HttpLibrary.mapHeaderWithExcelRowData(head, rows, logger);686 // } else {687 // Assert.fail("Header and rowdata length mismatch");688 // }689 // HttpLibrary.printCurrentDataValues(fromExcel);690 return fromExcel;691 }692 private String getRows(HashMap<String, String> header,693 ArrayList<String> head, int row) throws Exception,694 InterruptedException {695 Thread.sleep(3000);696 String rowData = HttpLibrary.getRowAtIndex(row + 2);697 for (int k = 0; k < 6; k++) {698 Thread.sleep(500);699 // System.out.println("for loop k value " + k);700 // System.out.println(rowData);701 if (!rowData.matches("[,]+")) {702 // check row data returns ,,,, or empty703 String[] rowValues = rowData.split("\\,");704 try {705 System.out.println(" Length " + head.size() + " : "706 + rowValues.length);707 if (rowValues[0].equals("") && rowValues[1].equals("")) {708 Thread.sleep(5000);709 rowData = HttpLibrary.getRowAtIndex(row + 2);710 System.out.println("Row" + " : "711 + Arrays.toString(rowValues));712 } else {713 System.out.println(Arrays.toString(rowValues));714 System.out.println("returning values");715 // rowValues = rowData.split("\\,");716 rowData = formatData(header, head, rowValues);717 break;718 }719 } catch (ArrayIndexOutOfBoundsException e) {720 rowData = HttpLibrary.getRowAtIndex(row + 2);721 }722 } else {723 if (k == 2) {724 break;725 }726 }727 }728 return rowData;729 // check return value + check whether multiple lines are handled or not730 // return rowData = formatData(header, head, rowValues);731 }732 // changing internal id value to labels for enum column and convert boolean733 // to lower case734 private String formatData(HashMap<String, String> header,735 ArrayList<String> head, String[] rowData) throws IOException,736 ParseException {737 // handle enum data if any738 String str = new String(739 Files.readAllBytes(Paths.get(System.getProperty("user.dir")740 + "//src//test//resources//enums.json")));741 org.json.simple.JSONObject enumsJson = (org.json.simple.JSONObject) new JSONParser()742 .parse(str);743 // Country..[?(@.internalId == "_angola")].name744 Object enums = Configuration.defaultConfiguration().jsonProvider()745 .parse(enumsJson.toString());746 for (int j = 0; j < header.size(); j++) {747 if (header.get(head.get(j)).equals("enum")) {748 System.out.println("enum feild found in header");749 System.out.println(head.get(j));750 if (rowData[j].startsWith("_")) {751 System.out.println("enum field: " + head.get(j));752 String[] data = head.get(j).toString().split("\\.");753 String enumField = data[data.length - 1];754 // Country..[?(@.internalId == "_angola")].name755 String q = enumField + "..[?(@.internalId == \""756 + rowData[j] + "\")].name";757 q = q.substring(0, 1).toUpperCase() + q.substring(1);758 System.out.println("query : " + q);759 String temp = remSpecialCharacters(JsonPath.read(enums, q)760 .toString());761 System.out.println("updated enum value from " + rowData[j]762 + " to " + temp);763 rowData[j] = temp;764 }765 }766 if (header.get(head.get(j)).equals("boolean")) {767 rowData[j] = rowData[j].toLowerCase();768 }769 }770 return Arrays.stream(rowData).collect(Collectors.joining(","));771 }772 public int getRecordId(org.json.JSONObject fromExcel) throws JSONException {773 try {774 String s = ((String) fromExcel.get(".internalId")).trim();775 if (s.equals("")) {776 Assert.fail("No data found in internal id column");777 }778 s = remSpecialCharacters(s);779 int i = Integer.parseInt(s);780 return i;781 } catch (NullPointerException e) {782 return 0;783 }784 }785 public org.json.JSONObject getFromNs(String recType, int[] arr,786 ExtentTest logger) throws IOException, ParseException,787 JSONException, InterruptedException {788 org.json.JSONObject fromNS = new org.json.JSONObject();789 ArrayList<String> actualData = new ArrayList<String>();790 ArrayList<String> head = templateHeader(CommonLibrary.getHeader());791 int maxArray = 1;792 for (int m = 0; m < arr.length; m++) {793 StringBuilder rl = HttpLibrary.doGET(recType, arr[m]);794 if (!rl.toString().equals("[]")) {795 JSONArray nsData = new JSONArray(rl.toString());796 org.json.JSONObject json = nsData.getJSONObject(0);797 // System.out.println(json.toString());798 // parsing JSON Response799 Configuration conf = Configuration.defaultConfiguration();800 Object document = conf.jsonProvider().parse(json.toString());801 // !! important System.out.println(JsonPath.read(document,802 // "$..addressbook[0].addressbookaddress.addressee").toString());803 ArrayList<String> res = new ArrayList<String>();804 res.add(0, "");805 // getting max length of sublist806 for (int j = 1; j < head.size(); j++) {807 // System.out.println(head.get(j).toString());808 String[] data = head.get(j).toString().split("\\.");809 // System.out.println(Arrays.toString(data));810 if (data.length > 2) {811 // $..addressbook.length()812 // System.out.println("$.." + data[2] + ".length()");813 String s = CommonLibrary.remSpecialCharacters(JsonPath814 .read(document, "$.." + data[2] + ".length()")815 .toString());816 if (maxArray < Integer.parseInt(s)) {817 maxArray = Integer.parseInt(s);818 System.out.println(maxArray);819 }820 }821 }822 // Print values from Ns JSON response823 for (int i = 0; i < maxArray; i++) {824 res = new ArrayList<String>();825 res.add(0, "");826 for (int j = 1; j < head.size(); j++) {827 String[] data = head.get(j).toString().split("\\.");828 String value = "";829 String Query = "";830 if (data.length > 2) {831 Query = generateJaywayQueryString(i, data,832 header.get(head.get(j))).toLowerCase();833 } else {834 Query = head.get(j).toLowerCase();835 }836 try {837 if (Query.contains("internalid")) {838 Query = Query.replaceAll("internalid", "id");839 if (Query.contains("addressbookaddress")) {840 res.add(j, "");841 } else {842 value = remSpecialCharacters(JsonPath.read(843 document, "$" + Query).toString());844 res.add(j, value);845 }846 } else {847 if (header.get(head.get(j)).equals("select")) {848 value = remSpecialCharacters(JsonPath.read(849 document, "$" + Query + ".name")850 .toString());851 res.add(j, value);852 } else if (header.get(head.get(j)).equals(853 "enum")) {854 value = remSpecialCharacters(JsonPath.read(855 document, "$" + Query + ".name")856 .toString());857 res.add(j, value);858 } else if (header.get(head.get(j)).equals(859 "boolean")) {860 value = remSpecialCharacters(JsonPath.read(861 document, "$" + Query).toString());862 value = value.toLowerCase();863 res.add(j, value);864 } else {865 value = remSpecialCharacters(JsonPath.read(866 document, "$" + Query).toString());867 res.add(j, value);868 }869 }870 } catch (PathNotFoundException e) {871 res.add(j, "");872 }873 }874 System.out.println("From NS: " + res);875 String[] values = new String[res.size()];876 // System.out.println(res.size());877 for (int j = 0; j < res.size(); j++) {878 // System.out.println(res.get(j));879 if (res.get(j).equals("") || res.get(j) == null) {880 values[j] = "";881 } else {882 values[j] = remSpecialCharacters(res.get(j));883 }884 }885 // Mapping header and row values as <Key,Value>886 // fromNS = HttpLibrary.mapHeaderWithExcelRowData(head,887 // values);888 actualData.add(Arrays.stream(values).collect(889 Collectors.joining(",")));890 // System.out.println(Arrays.toString(values));891 }892 }893 }894 fromNS = HttpLibrary895 .mapHeaderWithExcelRowData(head, actualData, logger);896 // HttpLibrary.printCurrentDataValues(fromNS);897 return fromNS;898 }899 public boolean compareData(org.json.JSONObject leftMap,900 org.json.JSONObject rightMap,901 com.aventstack.extentreports.ExtentTest logger)902 throws JSONException {903 logger.log(Status.INFO, leftMap + " with " + rightMap);904 if (leftMap == rightMap)905 return true;906 if (leftMap == null || rightMap == null907 || leftMap.length() != rightMap.length())908 return false;909 System.out.println("Comparing sheet data with NS data");910 try {911 JSONAssert.assertEquals(rightMap, leftMap, false);912 } catch (java.lang.AssertionError e) {913 System.out.println("error: " + e + "\n");914 logger.log(Status.FAIL, e);915 Assert.fail("Error" + e);916 }917 System.out.println("comparision is successful");918 logger.log(Status.PASS, "Sheet data and NS data Matached successfully");919 return true;920 }921 public enum App {...

Full Screen

Full Screen

Source:SeleniumBase.java Github

copy

Full Screen

...85 /**86 * 获取WebDriver87 */88 public static WebDriver getCurrentDriver(String... browerType) {89 final String brower = browerType != null && browerType.length == 1 ? browerType[0] : CURRENT_BROWER;90 if (ThreadDriverHolder.getDriver() == null) {91 WebDriver webDriver;92 if (brower.equals(BrowerTypeEnum.GOOGLE_CHROME.getCode())) {93 webDriver = createDriver();94 } else if (brower.equals(BrowerTypeEnum.PHANTOM_JS.getCode())) {95 webDriver = createDriverByPhantomJS();96 webDriver.manage().window().maximize();97 } else {98 throw new IllegalArgumentException("不合法的浏览器类型");99 }100 if (webDriver != null) {101 webDriver.manage().window().maximize();102 ThreadDriverHolder.setDriver(webDriver);103 } else {104 throw new RuntimeException("driver创建失败");105 }106 }107 return ThreadDriverHolder.getDriver();108 }109 /**110 * 为当前Webdriver设置cookie111 */112 public static void addCookie(String cookie) {113 WebDriver webDriver = getCurrentDriver();114 if (webDriver == null) {115 throw new IllegalStateException("webdriver初始化异常");116 }117 String[] cookies = cookie.split("; ");118 for (String s : cookies) {119 String[] tm = s.split("=");120 webDriver.manage().addCookie(new Cookie(tm[0], tm[1]));121 }122 }123 /**124 * 创建基于Headless chrome的无代理的webdriver125 */126 private static WebDriver createDriver() {127 DesiredCapabilities dec = DesiredCapabilities.chrome();128 System.setProperty("webdriver.chrome.driver", CHROME_DRIVER);129 ChromeOptions options = new ChromeOptions();130 options.setBinary(CHROME_PATH);131 options.addArguments("disable-infobars");132 //忽略证书错误133 options.addArguments("test-type");134 // 开启无头模式的关键设置135 options.addArguments("headless");136 //避免现阶段headless chrome可能引发的错误,后期可以去掉此项137 options.addArguments("disable-gpu");138 //允许selenium执行javascript脚本139 dec.setJavascriptEnabled(true);140 dec.setCapability(ChromeOptions.CAPABILITY, options);141 WebDriver driver = new ChromeDriver(options);142 return driver;143 }144 /**145 * 创建开启代理的基于headless chrome的webdriver146 */147 private static WebDriver createDriverByProxy() {148 String proxyHost = "";149 String proxyIp = "";150 //TODO :获取代理151 String proxIpAndPort = proxyHost + ":" + proxyIp;152 DesiredCapabilities dec = DesiredCapabilities.chrome();153 Proxy proxy = new Proxy();154 proxy.setHttpProxy(proxIpAndPort).setSslProxy(proxIpAndPort);155 dec.setCapability(CapabilityType.ForSeleniumServer.AVOIDING_PROXY, true);156 dec.setCapability(CapabilityType.ForSeleniumServer.ONLY_PROXYING_SELENIUM_TRAFFIC, true);157 dec.setCapability(CapabilityType.PROXY, proxy);158 System.setProperty("webdriver.chrome.driver", CHROME_DRIVER);159 ChromeOptions chromeOptions = new ChromeOptions();160 chromeOptions.setBinary(CHROME_PATH);161 chromeOptions.addArguments("test-type");162 chromeOptions.addArguments("headless");163 chromeOptions.addArguments("disable-gpu");164 chromeOptions.addArguments("disable-infobars");165 dec.setCapability(ChromeOptions.CAPABILITY, chromeOptions);166 dec.setJavascriptEnabled(true);167 WebDriver driver = new ChromeDriver(dec);168 return driver;169 }170 /**171 * 创建基于phantomJS的webdriver172 */173 private static WebDriver createDriverByPhantomJS() {174 WebDriver driver;175 DesiredCapabilities sCaps = new DesiredCapabilities();176 sCaps.setJavascriptEnabled(true);177 sCaps.setCapability("takesScreenshot", false);178 sCaps.setCapability(PhantomJSDriverService.PHANTOMJS_PAGE_SETTINGS_PREFIX + "userAgent",179 "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11");180 sCaps.setCapability(CapabilityType.SUPPORTS_ALERTS, true);181 sCaps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, PHANTOM_DRIVER);182 ArrayList<String> cliArgsCap = new ArrayList<String>();183 cliArgsCap.add("--web-security=false");184 cliArgsCap.add("--ssl-protocol=any");185 cliArgsCap.add("--ignore-ssl-errors=true");186 sCaps.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS, cliArgsCap);187 // Control LogLevel for GhostDriver, via CLI arguments188 sCaps.setCapability(PhantomJSDriverService.PHANTOMJS_GHOSTDRIVER_CLI_ARGS, new String[]{189 "--logLevel=" + "INFO"190 });191 driver = new PhantomJSDriver(sCaps);192 //设置Driver超时等属性193 driver.manage().timeouts().implicitlyWait(ELEMENT_SEARCH_TIMEOUT,194 TimeUnit.SECONDS);195 driver.manage().timeouts().pageLoadTimeout(PAGE_LOAD_TIMEOUT,196 TimeUnit.SECONDS);197 driver.manage().timeouts().setScriptTimeout(SCRIPT_EXECUTE,198 TimeUnit.SECONDS);199 return driver;200 }201 public static void quitDriver() {202 WebDriver webDriver = ThreadDriverHolder.getDriver();203 if (webDriver != null) {204 webDriver.quit();205 ThreadDriverHolder.clearDriver();206 }207 }208 /**209 * 获取web元素210 */211 public static WebElement getWebElement(By by) {212 if (checkElementExsist(by)) {213 return getCurrentDriver().findElement(by);214 } else {215 return null;216 }217 }218 /**219 * 获取一组web元素220 */221 public static List<WebElement> getWebElements(By by) {222 if (checkElementExsist(by)) {223 return getCurrentDriver().findElements(by);224 } else {225 return null;226 }227 }228 /**229 * 等待临时弹窗消失230 */231 public static void waitForDialogDisappear(By by) {232 try {233 new WebDriverWait(getCurrentDriver(), 15).until(ExpectedConditions.invisibilityOfElementLocated(by));234 } catch (Exception e) {235 quitDriver();236 if (e instanceof TimeoutException) {237 throw new IllegalStateException("等待弹窗消失超时");238 }239 throw e;240 }241 }242 /**243 * 截取当前屏幕中的页面244 */245 public static String takeScreenShot() {246 byte[] bs = ((TakesScreenshot) getCurrentDriver()).getScreenshotAs(OutputType.BYTES);247 String filePath = null;248 if (bs != null && bs.length > 0) {249 FileOutputStream fileOutputStream = null;250 try {251 filePath = SCREENSHOT_PATH + "/" + System.currentTimeMillis() + ".gif";252 fileOutputStream = new FileOutputStream(new File(filePath));253 fileOutputStream.write(bs);254 fileOutputStream.close();255 } catch (IOException e) {256 e.printStackTrace();257 } finally {258 try {259 fileOutputStream.close();260 } catch (IOException e) {261 e.printStackTrace();262 }...

Full Screen

Full Screen

Source:AmountControlDataDownloader.java Github

copy

Full Screen

...194 195 (new WebDriverWait(driver, 60)).until(ExpectedConditions.presenceOfElementLocated(By.tagName("table")));196 ((JavascriptExecutor)driver).executeScript(197 "var imgs = document.getElementsByTagName('img'); " +198 "var len=imgs.length; " +199 "for(var i=len-1; i>=0; i--) {imgs[i].parentNode.removeChild(imgs[i]);} ");200 201 pageLoaded = true;202 }203 204 type.download(driver, finalOutput);205 206 }207 if(pageLoaded) {208 driver.switchTo().window(newWindows[0]);209 }210// break;211 }212 } ...

Full Screen

Full Screen

Source:StepImplementation.java Github

copy

Full Screen

...47 getElement(locatorValue).click();48 }49 @Step({" delete the data in the <locatorValue> "})50 public void delete(String locatorValue) throws Exception {51 int length = getElement(locatorValue).getAttribute("value").length();52 for (int i = 0; i < length; ++i) {53 getElement(locatorValue).sendKeys(Keys.BACK_SPACE);54 }55 }56 @Step({"Send keys <input> in <locatorValue>."})57 public void sendKeys(String input, String locatorValue) throws Exception {58 getElement(locatorValue).sendKeys(input);59 }60 @Step({"Send keys number <input> in <locatorValue>."})61 public void sendKeysNumber(String input,String locatorValue) throws Exception {62 char[] ch=input.toCharArray();63 for(int i=0;i<ch.length;i++) {64 getElement(locatorValue).sendKeys(String.valueOf(ch[i]));65 }66 }67 @Step("<locatorValue> display element.")68 public void isDisplay(String locatorValue) throws Exception {69 Assertions.assertTrue(getElement(locatorValue).isDisplayed());70 }71 @Step("Stop the test for <second> seconds.")72 public void pauseTest(int second) throws InterruptedException {73 Thread.sleep((second * 1000L));74 }75 @Step({"The text of the <locatorValue> element matches <text>."})76 public void assertText(String locatorValue, String text) throws Exception {77 var locatorText = getElement(locatorValue).getText().replaceAll("\\s","");...

Full Screen

Full Screen

Source:ElementUtil.java Github

copy

Full Screen

...108 }109 public static String getValue(WebElement elem) {110 return (elem.getAttribute("value"));111 }112 public static Boolean isFieldLengthEqualsMaxlength(WebElement elem) {113 // check size field of Cost field 114 // to see if the Cost field size length is not less than the max length115 int size = Integer.parseInt(elem.getAttribute("size"));116 int maxlength = Integer.parseInt(elem.getAttribute("maxlength"));117 if (size == maxlength) {118 return true;119 } else120 return false; 121 }122 public static boolean checkButtonIsDisabled(WebElement button) {123 if (!button.isEnabled()) 124 return true;125 else126 return false;127 }128 public static double calculateExpectedTotalCost(String selected, String quantityStr) {129 double totalCost = 0;130 // calculate the expected total cost131 if (selected.contains("$")) {...

Full Screen

Full Screen

Source:TestLogin.java Github

copy

Full Screen

...78 System.out.println(rp.twoSum(numbers,9)[1]) ;79 System.out.println(rp.twoSum(numbers,9)[0]);80 System.out.println(rp.reverseInt(4567889));81 int arr[] = {60,20,20,30,30,60,40,50,50};82 int length = arr.length;83 length = removeDuplicateElements(arr, length);84 for (int i = 0; i < length; i++)85 System.out.print(arr[i]+" ");86 */87 //printing array elements88 }89 }...

Full Screen

Full Screen

Source:KeyCombination.java Github

copy

Full Screen

...23 this.driver = driver;24 String[] parts = keyCombination25 .replaceAll("(^\\{+|}+$)", "") // trim braces26 .split("\\+");27 String lastElement = parts[parts.length - 1].trim();28 textKeys = isKeyboardKey(lastElement)29 ? convertToSeleniumKey(lastElement).toString()30 : lastElement;31 String[] restOfElements = Arrays.copyOf(parts, parts.length - 1);32 keysModifiers = Stream.of(restOfElements)33 .map(String::trim)34 .map(this::convertToSeleniumKey)35 .collect(Collectors.toList());36 }37 /**38 * Type key combination in currently focused element.39 */40 public void type() {41 Actions actions = new Actions(driver);42 Stack<Keys> keysToRelease = new Stack<>();43 for (Keys key : keysModifiers) {44 actions.keyDown(key);45 keysToRelease.push(key);...

Full Screen

Full Screen

Source:CreateLead.java Github

copy

Full Screen

...40 41 WebElement Source3 = driver.findElementById("createLeadForm_industryEnumId");42 Select dropDown3 = new Select(Source3);43 List<WebElement> option = dropDown3.getOptions();44 int length = option.size();45 dropDown3.selectByIndex(length-2);46 /* for(WebElement each : option)47 {48 System.out.println(each.getText());49 }*/50 WebElement Source4 = driver.findElementById("createLeadForm_ownershipEnumId");51 Select dropDown4 = new Select(Source4);52 //driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);53 54 55 try {56 dropDown4.selectByValue("OWN_PUBLIC_CORPP");57 }58 catch(NoSuchElementException e)59 { ...

Full Screen

Full Screen

length

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.By;2import org.openqa.selenium.Keys;3import org.openqa.selenium.WebDriver;4import org.openqa.selenium.WebElement;5import org.openqa.selenium.chrome.ChromeDriver;6import org.openqa.selenium.interactions.Actions;7public class KeysLength {8public static void main(String[] args) {9 System.setProperty("webdriver.chrome.driver", "C:\\Users\\sudhakar\\Downloads\\chromedriver_win32\\chromedriver.exe");10 WebDriver driver = new ChromeDriver();11 WebElement searchBox = driver.findElement(By.name("q"));12 Actions act = new Actions(driver);13 act.sendKeys(searchBox, Keys.CONTROL, "a").perform();14 System.out.println(Keys.CONTROL.length());15 driver.close();16}17}

Full Screen

Full Screen

length

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.By;2import org.openqa.selenium.Keys;3import org.openqa.selenium.WebDriver;4import org.openqa.selenium.WebElement;5import org.openqa.selenium.chrome.ChromeDriver;6public class KeysDemo {7 public static void main(String[] args) throws InterruptedException {8 System.setProperty("webdriver.chrome.driver", "C:\\Users\\User\\Downloads\\chromedriver_win32\\chromedriver.exe");9 WebDriver driver = new ChromeDriver();10 WebElement searchBox = driver.findElement(By.name("q"));11 searchBox.sendKeys("Selenium");12 searchBox.sendKeys(Keys.ENTER);13 Thread.sleep(3000);14 driver.quit();15 }16}

Full Screen

Full Screen

length

Using AI Code Generation

copy

Full Screen

1package org.openqa.selenium;2public class EnumKeys {3 public static void main(String[] args) {4 int keysCount = Keys.values().length;5 System.out.println("Number of Keys: " + keysCount);6 int ordinal = Keys.ARROW_DOWN.ordinal();7 System.out.println("Ordinal value of ARROW_DOWN key: " + ordinal);8 String keyName = Keys.valueOf("ARROW_DOWN").toString();9 System.out.println("Name of ARROW_DOWN key: " + keyName);10 }11}

Full Screen

Full Screen

length

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.Keys;2public class EnumKeys {3 public static void main(String[] args) {4 int numKeys = Keys.values().length;5 System.out.println("Number of keys defined in the enum: " + numKeys);6 for (int i = 0; i < numKeys; i++) {7 System.out.println(Keys.values()[i].name());8 }9 }10}

Full Screen

Full Screen

length

Using AI Code Generation

copy

Full Screen

1List<Keys> keys = new ArrayList<Keys>();2int len = Keys.values().length;3for(int i=0;i<len;i++){4 keys.add(Keys.values()[i]);5}6System.out.println(keys);

Full Screen

Full Screen

length

Using AI Code Generation

copy

Full Screen

1package org.openqa.selenium;2public class EnumKeys {3 public static void main(String[] args) {4 Keys[] keys = Keys.values();5 System.out.println("The number of elements in the enum is " + keys.length);6 System.out.println("The enum elements are:");7 for (Keys key : keys) {8 System.out.println(key);9 }10 System.out.println("The length of the enum is " + keys.length);11 System.out.println("The ordinal of each enum element is:");12 for (Keys key : keys) {13 System.out.println(key.ordinal());14 }15 System.out.println("The name of each enum element is:");16 for (Keys key : keys) {17 System.out.println(key.name());18 }19 System.out.println("The value of each enum element is:");20 for (Keys key : keys) {21 System.out.println(key.getValue());22 }23 }24}

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