// Method checking if the edited profile is displayed back to the user and if illegal string like // URL and email id are stripped off from "profile essay" sections private void verifyChanges() { List<WebElement> allElements = driver.findElements(By.cssSelector("div[id='about_myself'] p")); for (WebElement element1 : allElements) { if (element1.getText().contains("www.") || element1.getText().contains(".com")) ; ripOffTextAboutMe++; } List<WebElement> allElements2 = driver.findElements(By.cssSelector("div[id='who_im_looking_for'] p")); for (WebElement element2 : allElements2) { if (element2.getText().contains("www.") || element2.getText().contains(".com")) ; ripOffTextPartnerSearch++; } List<WebElement> allElement3 = driver.findElements(By.cssSelector("ul[class='profileInformation'] li")); for (WebElement element3 : allElement3) { // System.out.println(element3.getText()); if (element3.getText().contains("Mixed") || element3.getText().contains("4ft. 10in.")) profileChangeCheck++; } if (profileChangeCheck > 0) System.out.println("SUCCESS: The changes made in the basic profile are visible"); if (ripOffTextAboutMe != 0) System.out.println( "SUCCESS: The About Myself section has ripped off any illegal strings like URL and Email id"); if (ripOffTextPartnerSearch != 0) System.out.println( "SUCCESS: The What I am Looking For section has ripped off any illegal strings like URL and Email id"); }
public static List<WebElement> createWebElementsList(WebDriver driver, By by) { List<WebElement> webElements; driver.manage().timeouts().implicitlyWait(0, TimeUnit.MILLISECONDS); // Quickly webElements = driver.findElements(by); driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS); return webElements; }
public static void main(String[] args) { String baseUrl = "http://newtours.demoaut.com/"; WebDriver driver = new FirefoxDriver(); String underConsTitle = "Under Construction: Mercury Tours"; // Creates result string driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.get(baseUrl); List<WebElement> linkElements = driver.findElements(By.tagName("a")); // Creates lists from <a> tags String[] linkTexts = new String[linkElements.size()]; int i = 0; // extract the link texts of each link element for (WebElement e : linkElements) { linkTexts[i] = e.getText(); i++; } // test each link by looping over them for (String t : linkTexts) { driver.findElement(By.linkText(t)).click(); if (driver.getTitle().equals(underConsTitle)) { System.out.println("\"" + t + "\"" + " is under construction."); } else { System.out.println( "\"" + t + "\"" // print results to console + " is working."); } driver.navigate().back(); } driver.quit(); }
@Test @Ignore( "I would love for this to work consistently but it fails too often between releases to use as an example") public void multiSelectWithUserInteractions() { WebElement multiSelect; multiSelect = driver.findElement(By.cssSelector("select[multiple='multiple']")); List<WebElement> multiSelectOptions = multiSelect.findElements(By.tagName("option")); // in real life, clicking on a multi select item without holding down // CTRL will deselect all others and select only that one item Actions actions = new Actions(driver); actions .click(multiSelectOptions.get(0)) .click(multiSelectOptions.get(1)) .click(multiSelectOptions.get(2)) .perform(); clickSubmitButton(); new WebDriverWait(driver, 10).until(ExpectedConditions.titleIs("Processed Form Details")); assertEquals( "Expected only 1 match", 1, driver.findElements(By.cssSelector("[id^='_valuemultipleselect']")).size()); }
private boolean clickNext(WebDriver driver) { while (true) { boolean clicked = false; int iteration = 0; By by = By.className("show-next"); clickCloseModalIfAny(driver); for (WebElement el : driver.findElements(by)) { try { waitdriver.until(ExpectedConditions.elementToBeClickable(by)); el.click(); clicked = true; return true; } catch (Exception ex) { } } if (!clicked) { iteration++; continue; } if (!clicked && iteration > 3) { log.error("Element not clickable"); return false; } } }
@Ignore // Ignored because you need to kickstart Python SimpleHTTPServer before it can run @Test public void shouldSwitchToTheRightFrame_issue226() { // NOTE: before starting this test, // run `python -m SimpleHTTPServer` from within `test/testcase-issue_226`. // This will launch a minimal webserver to serve the pages for this test. WebDriver d = getDriver(); // Load "outside.html" and check it's the right one d.get("http://localhost:8000/outside.html"); assertTrue(d.getPageSource().contains("Editing testDotAtEndDoesNotDelete")); assertEquals(2, d.findElements(By.tagName("iframe")).size()); // Find the iframe with class "gwt-RichTextArea" WebElement iframeRichTextArea = d.findElement(By.className("gwt-RichTextArea")); // Switch to the iframe via WebElement and check it's the right one d.switchTo().frame(iframeRichTextArea); assertEquals(0, d.findElements(By.tagName("title")).size()); assertFalse(d.getPageSource().contains("Editing testDotAtEndDoesNotDelete")); assertEquals(0, d.findElements(By.tagName("iframe")).size()); // Switch back to the main frame and check it's the right one d.switchTo().defaultContent(); assertEquals(2, d.findElements(By.tagName("iframe")).size()); // Switch again to the iframe, this time via it's "frame number" (i.e. 0 to n) d.switchTo().frame(0); assertEquals(0, d.findElements(By.tagName("title")).size()); assertFalse(d.getPageSource().contains("Editing testDotAtEndDoesNotDelete")); assertEquals(0, d.findElements(By.tagName("iframe")).size()); // Switch back to the main frame and check it's the right one d.switchTo().defaultContent(); assertEquals(2, d.findElements(By.tagName("iframe")).size()); // Switch to the second frame via it's "frame number" d.switchTo().frame(1); assertEquals(1, d.findElements(By.tagName("title")).size()); assertEquals(0, d.findElements(By.tagName("iframe")).size()); assertTrue(d.getPageSource().contains("WYSIWYG Editor Input Template")); // Switch again to the main frame d.switchTo().defaultContent(); assertEquals(2, d.findElements(By.tagName("iframe")).size()); }
/** * inchide dialogul cu promotiile * * @param driver */ private void clickCloseModalIfAny(WebDriver driver) { try { for (WebElement el : driver.findElements(By.className("box-content"))) { el.click(); } } catch (Exception ex) { // nothing } }
@Test(expected = TimeoutException.class) public void shouldTimeoutWhileChangingIframeSource() { final String iFrameId = "iframeId"; // Define HTTP response for test server.setGetHandler( new HttpRequestCallback() { @Override public void call(HttpServletRequest req, HttpServletResponse res) throws IOException { String pathInfo = req.getPathInfo(); ServletOutputStream out = res.getOutputStream(); if (pathInfo.endsWith("iframe_content.html")) { // nested frame 1 out.println("iframe content"); } else { // main page out.println( "<html>\n" + "<body>\n" + " <iframe id='" + iFrameId + "'></iframe>\n" + " <script>\n" + " setTimeout(function() {\n" + " document.getElementById('" + iFrameId + "').src='iframe_content.html';\n" + " }, 2000);\n" + " </script>\n" + "</body>\n" + "</html>"); } } }); // Launch Driver against the above defined server WebDriver d = getDriver(); d.get(server.getBaseUrl()); // Switch to iframe d.switchTo().frame(iFrameId); assertEquals(0, d.findElements(By.id(iFrameId)).size()); assertFalse(d.getPageSource().toLowerCase().contains("iframe content")); new WebDriverWait(d, 5) .until( new Predicate<WebDriver>() { @Override public boolean apply(@Nullable WebDriver driver) { assertEquals(0, driver.findElements(By.id(iFrameId)).size()); return (Boolean) ((JavascriptExecutor) driver).executeScript("return false;"); } }); }
private void gotoUserAdmin() { System.out.println("Going to UserAdmin-module"); selenium.selectFrame("relative=top"); driver.findElements(new By.ByLinkText("User Admin")).get(1).click(); selenium.waitForFrameToLoad("content", "30000"); captureScreenshot(); }
public static void main(String args[]) throws InterruptedException { ProfilesIni profile = new ProfilesIni(); FirefoxProfile ffprofile = profile.getProfile("default"); WebDriver driver = new FirefoxDriver(ffprofile); driver.get("http://csgorage.com/free-raffles/current"); List<WebElement> raffleDivs = driver.findElements(By.cssSelector("" + ".raffle_box_lg")); for (int i = 0; i < raffleDivs.size(); i++) { raffleDivs.get(i).findElement(By.cssSelector("a")).click(); int timer = 20; int currentTime = 0; JavascriptExecutor js = (JavascriptExecutor) driver; do { js.executeScript("window.scrollBy(0,250)", ""); Thread.sleep(5000); currentTime++; } while (currentTime < timer); itemEntry(driver); driver.navigate().back(); raffleDivs = driver.findElements(By.cssSelector("" + ".raffle_box_lg")); } }
/** * User interactions can be unpredictable. Seem good with mouse or keyboard but less so with * combined mouse + keyboard * * <p>Use when 'normal' webdriver does not work * * <p>e.g. a normal webDriver click does a ctrl+click an action does a click * * <p>but using action to do a ctrl+click does not work reliably for everybody */ @Test public void multiSelect123WithUserInteractions() { WebElement multiSelect; multiSelect = driver.findElement(By.cssSelector("select[multiple='multiple']")); List<WebElement> multiSelectOptions = multiSelect.findElements(By.tagName("option")); // in real life, clicking on a multi select item without holding down // CTRL will deselect all others and select only that one item Actions actions = new Actions(driver); // actions.keyUp(Keys.CONTROL).perform(); // click on the first one // also deselects number 4 actions.click(multiSelectOptions.get(0)).perform(); // Press Control + Left mouse button for 2 and 3 actions .keyDown(Keys.CONTROL) .click(multiSelectOptions.get(1)) .click(multiSelectOptions.get(2)) .keyUp(Keys.CONTROL) .build() .perform(); clickSubmitButton(); new WebDriverWait(driver, 10).until(ExpectedConditions.titleIs("Processed Form Details")); List<WebElement> selectedItems = driver.findElements(By.cssSelector("[id^='_valuemultipleselect']")); try { assertEquals("Expected 3 matches", 3, selectedItems.size()); assertEquals("ms1", selectedItems.get(0).getText()); assertEquals("ms2", selectedItems.get(0).getText()); assertEquals("ms3", selectedItems.get(0).getText()); fail("What browser and WebDriver combination did you use? This normally fails"); } catch (AssertionFailedError e) { assertTrue("either I've done something wrong or this is not reliable enough", true); } }
private void saveFile(WebDriver driver) { int iteration = 0; while (iteration < 3) { try { for (WebElement el : driver.findElements(By.className("flights-container"))) { if (el.getText().contains("outbound")) { log.info( "Saving file date={} fromDest={} toDest={} fileIndex={}", today, fromDest, toDest, fileIndex); try { Path folder = Paths.get(folderLocation + "/" + today); if (!Files.exists(folder)) { Files.createDirectory(folder); } Files.write( Paths.get( folderLocation + "/" + today + "/" + fileSimpleDateFormat.format(new Date()) + "_" + fromDest.replaceAll("/", "-") + "_" + toDest.replaceAll("/", "-") + "_" + fileIndex + ".txt"), Lists.newArrayList(el.getText())); fileIndex++; return; } catch (IOException e) { log.error("Error saving file", e); } } } } catch (StaleElementReferenceException ex) { log.warn("Stale..."); iteration++; } } }
// li.active>span.next public static void main(String[] args) { if (args.length < 2) { System.out.println("please input two paremeter!"); System.exit(0); } String filePath = args[0]; String phantomJsPath = args[1]; DesiredCapabilities cap = DesiredCapabilities.phantomjs(); cap.setCapability( PhantomJSDriverService.PHANTOMJS_CLI_ARGS, new String[] { // "--webdriver-loglevel=DEBUG", // "--proxy=org.openqa.grid.selenium.proxy.DefaultRemoteProxy", }); cap.setCapability( PhantomJSDriverService.PHANTOMJS_PAGE_CUSTOMHEADERS_PREFIX + "Accept-Language", "zh_CN"); // cap.setCapability("phantomjs.page.settings.userAgent","Mozilla/5.0 (Macintosh; Intel Mac OS X // 10.9; rv:25.0) Gecko/20100101 Firefox/25.0"); // "C:\\Users\\Administrator\\Desktop\\phantomjs-2.0.0-windows\\bin\\phantomjs.exe" cap.setCapability("phantomjs.binary.path", phantomJsPath); cap.setJavascriptEnabled(true); driver = new PhantomJSDriver(cap); WebDriverWait wait = null; wait = new WebDriverWait(driver, 60); driver.get(URL); /*try { Thread.currentThread().sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); }*/ // screenShot((TakesScreenshot) driver, "/home/admin/"+"mo9"+c+".png"); List<WebElement> nextElement = null; ArrayList<String> credits = new ArrayList<String>(); int prePage = 1; int curPage = c; BufferedWriter br = null; File f = new File(filePath); try { br = new BufferedWriter(new FileWriter(f, true)); br.write("mo9账号,真实姓名,身份证号,欠款金额,逾期天数"); br.write("\r\n"); } catch (IOException e1) { e1.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } while (!isLast) { List<WebElement> elements = null; try { elements = wait.until( ExpectedConditions.visibilityOfAllElementsLocatedBy( By.cssSelector("div.faith-list>dl.fs12"))); } catch (Exception e) { e.printStackTrace(); driver.close(); driver.quit(); while (elements == null) { try { Thread.currentThread().sleep(720000); // c=((curPage/15)*15)+1; // curPage=c; driver = new PhantomJSDriver(cap); // driver=new FirefoxDriver(binary,profile); wait = new WebDriverWait(driver, 60); driver.get("https://www.mo9.com/creditCenter/p/" + curPage); elements = wait.until( ExpectedConditions.visibilityOfAllElementsLocatedBy( By.cssSelector("div.faith-list>dl.fs12"))); } catch (Exception e1) { e1.printStackTrace(); } } } System.out.println(curPage); for (WebElement element : elements) { StringBuffer sb = new StringBuffer(); String acount = element.findElement(By.cssSelector("div.faith-list>dl.fs12>dt.row01")).getText(); String name = element.findElement(By.cssSelector("div.faith-list>dl.fs12>dd.row02")).getText(); String certiCard = element.findElement(By.cssSelector("div.faith-list>dl.fs12>dd.row03")).getText(); String debt = element.findElement(By.cssSelector("div.faith-list>dl.fs12>dd.row04")).getText(); String overDue = element.findElement(By.cssSelector("div.faith-list>dl.fs12>dd.row05")).getText(); sb.append(acount + "," + name + "," + certiCard + "," + debt + "," + overDue); credits.add(sb.toString()); } nextElement = driver.findElements(By.cssSelector("li>a.next")); if (credits.size() % 150 == 0 || nextElement.size() == 0) { try { br = new BufferedWriter(new FileWriter(f, true)); for (String str : credits) { br.write(str); br.write("\r\n"); } credits.clear(); } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } try { // Random r=new Random(100); // int n=r.nextInt(90); Thread.currentThread().sleep(20000); } catch (InterruptedException e) { e.printStackTrace(); } } if (nextElement.size() == 0) { isLast = true; } else { nextElement.get(0).click(); curPage++; try { Thread.currentThread().sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
public List<WebElement> findElements(By by) { return driver.findElements(by); }
// get WebElements public List<WebElement> getWebElements(String locator) { List<WebElement> elements = driver.findElements(By.cssSelector(locator)); return elements; }
public List<WebElement> getWebElementsByCss(String locator) { List<WebElement> elementList = new ArrayList<WebElement>(); elementList = driver.findElements(By.cssSelector(locator)); return elementList; }
public List<WebElement> findElements(WebLocator el) { return driver.findElements(el.getSelector()); }
/** * @return list of web elements found based on all locators * @throws WidgetException */ private List<WebElement> findElements() throws WidgetException { String locator = getLocator(); getGUIDriver().selectLastFrame(); WebDriver wd = getGUIDriver().getWrappedDriver(); List<WebElement> webElements; try { webElements = wd.findElements(By.xpath(locator)); if (webElements != null && webElements.size() > 0) { for (WebElement we : webElements) { highlight(we, HIGHLIGHT_MODES.FIND); } return webElements; } } catch (Exception e) { } try { webElements = wd.findElements(By.id(locator)); if (webElements != null && webElements.size() > 0) { for (WebElement we : webElements) { highlight(we, HIGHLIGHT_MODES.FIND); } return webElements; } } catch (Exception e) { } try { webElements = wd.findElements(By.name(locator)); if (webElements != null && webElements.size() > 0) { for (WebElement we : webElements) { highlight(we, HIGHLIGHT_MODES.FIND); } return webElements; } } catch (Exception e) { } try { webElements = wd.findElements(By.cssSelector(locator)); if (webElements != null && webElements.size() > 0) { for (WebElement we : webElements) { highlight(we, HIGHLIGHT_MODES.FIND); } return webElements; } } catch (Exception e) { } try { webElements = wd.findElements(By.className(locator)); if (webElements != null && webElements.size() > 0) { for (WebElement we : webElements) { highlight(we, HIGHLIGHT_MODES.FIND); } return webElements; } } catch (Exception e) { } try { webElements = wd.findElements(By.tagName(locator)); if (webElements != null && webElements.size() > 0) { for (WebElement we : webElements) { highlight(we, HIGHLIGHT_MODES.FIND); } return webElements; } } catch (Exception e) { } throw new NoSuchElementException("Could not find elements matching " + locator); }