List of usage examples for org.openqa.selenium WebDriver findElements
@Override List<WebElement> findElements(By by);
From source file:com.maoyan.pf.webcollector.spider.ShowrateCrawler.java
License:Open Source License
public static void main(String[] args) throws Exception { Executor executor = new Executor() { @Override//from w ww. j ava 2 s .c o m public void execute(CrawlDatum datum, CrawlDatums next) throws Exception { MongoClient mongoClient = new MongoClient("localhost", 27017); // ? // DBCollection dbCollection = mongoClient.getDB("maoyan_crawler").getCollection("rankings_am"); DB db = mongoClient.getDB("maoyan_crawler"); // ????? Set<String> colls = db.getCollectionNames(); for (String s : colls) { // Collection(?"") if (s.equals("show_rate")) { db.getCollection(s).drop(); } } DBCollection dbCollection = db.getCollection("show_rate"); // ProfilesIni pi = new ProfilesIni(); // FirefoxProfile profile = pi.getProfile("default"); WebDriver driver = new FirefoxDriver(); driver.manage().window().maximize(); driver.manage().timeouts().pageLoadTimeout(3, TimeUnit.SECONDS); // driver.setJavascriptEnabled(false); System.out.println("??\n"); driver.get(datum.getUrl()); // System.out.println(driver.getPageSource()); List<WebElement> movie_name = driver .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c1 lineDot']")); List<WebElement> boxoffice_rate = driver .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c2 red']")); List<WebElement> visit_pershow = driver .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c3 gray']")); WebElement title = driver.findElement(By.xpath("//p[@id='pieTip']")); for (int i = 0; i < movie_name.size(); i++) { String movie_name_val = movie_name.get(i).getText(); String boxofficerate_val = boxoffice_rate.get(i).getText(); String visit_pershow_val = visit_pershow.get(i).getText(); BasicDBObject dbObject = new BasicDBObject(); dbObject.append("title", title.getText()).append("is_gold", "?") .append("show_type", "?").append("movie_name", movie_name_val) .append("boxoffice_rate", boxofficerate_val).append("visit_pershow", visit_pershow_val); dbCollection.insert(dbObject); } System.out.println("?\n"); WebElement click_gold = driver.findElement(By.id("playPlan_time")); click_gold.click(); String gold_seat = driver.getWindowHandle(); driver.switchTo().window(gold_seat); List<WebElement> movie_name_gold = driver .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c1 lineDot']")); List<WebElement> boxoffice_rate_gold = driver .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c2 red']")); List<WebElement> visit_pershow_gold = driver .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c3 gray']")); WebElement title_gold = driver.findElement(By.xpath("//p[@id='pieTip']")); for (int i = 0; i < movie_name_gold.size(); i++) { String movie_name_val = movie_name_gold.get(i).getText(); String boxofficerate_val = boxoffice_rate_gold.get(i).getText(); String visit_pershow_val = visit_pershow_gold.get(i).getText(); BasicDBObject dbObject = new BasicDBObject(); dbObject.append("title", title_gold.getText()).append("is_gold", "") .append("show_type", "?").append("movie_name", movie_name_val) .append("boxoffice_rate", boxofficerate_val).append("visit_pershow", visit_pershow_val); dbCollection.insert(dbObject); } System.out.println("?\n"); WebElement click_vist = driver.findElement(By.xpath("//*[@id='show--type']")); click_vist.click(); String gold_vist = driver.getWindowHandle(); driver.switchTo().window(gold_vist); List<WebElement> movie_name_gold_visit = driver .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c1 lineDot']")); List<WebElement> boxoffice_rate_gold_visit = driver .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c2 red']")); List<WebElement> visit_pershow_gold_visit = driver .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c3 gray']")); WebElement title_gold_visit = driver.findElement(By.xpath("//p[@id='pieTip']")); for (int i = 0; i < movie_name_gold_visit.size(); i++) { String movie_name_val = movie_name_gold_visit.get(i).getText(); String boxofficerate_val = boxoffice_rate_gold_visit.get(i).getText(); String visit_pershow_val = visit_pershow_gold_visit.get(i).getText(); BasicDBObject dbObject = new BasicDBObject(); dbObject.append("title", title_gold_visit.getText()).append("is_gold", "") .append("show_type", "").append("movie_name", movie_name_val) .append("boxoffice_rate", boxofficerate_val).append("visit_pershow", visit_pershow_val); dbCollection.insert(dbObject); } System.out.println("?\n"); click_gold.click(); String normal_seat = driver.getWindowHandle(); driver.switchTo().window(normal_seat); List<WebElement> movie_name_normal_seat = driver .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c1 lineDot']")); List<WebElement> boxoffice_rate_normal_seat = driver .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c2 red']")); List<WebElement> visit_pershow_normal_seat = driver .findElements(By.xpath("//div[@id='playPlan_table']/ul/li[@class='c3 gray']")); WebElement title_normal_seat = driver.findElement(By.xpath("//p[@id='pieTip']")); for (int i = 0; i < movie_name_normal_seat.size(); i++) { String movie_name_val = movie_name_normal_seat.get(i).getText(); String boxofficerate_val = boxoffice_rate_normal_seat.get(i).getText(); String visit_pershow_val = visit_pershow_normal_seat.get(i).getText(); BasicDBObject dbObject = new BasicDBObject(); dbObject.append("title", title_normal_seat.getText()).append("is_gold", "?") .append("show_type", "").append("movie_name", movie_name_val) .append("boxoffice_rate", boxofficerate_val).append("visit_pershow", visit_pershow_val); dbCollection.insert(dbObject); } driver.close(); driver.quit(); mongoClient.close(); } }; //DBDBManager DBManager manager = new BerkeleyDBManager("maoyan"); //Crawler?DBManagerExecutor Crawler crawler = new Crawler(manager, executor); crawler.addSeed("http://pf.maoyan.com/show/rate"); crawler.start(1); }
From source file:com.mediamelon.UserActions.java
void addAccount(WebDriver driver, List<String> formData) { //Verify if the user is logged in as Super User to create a new account. //If not, display message and return //Verify if the user is logged in String pageTitle = driver.getTitle(); Assert.assertEquals(pageTitle, "MediaMelon - Home"); String fullName = driver.findElement(By.xpath("//div[@class='row data']/div/div[1]/p[2]")).getText(); String role = driver.findElement(By.xpath("//div[@class='row data']/div/div[3]/p[2]")).getText(); if (fullName.equalsIgnoreCase("Super User") && role.equalsIgnoreCase("admin")) { System.out.println("List of Accounts is displayed"); //expand the settings menu option and click on Account Management List<WebElement> dropDownOptions = driver.findElements(By.className("dropdown-toggle")); dropDownOptions.get(0).click();/* w w w . ja v a 2 s . co m*/ WebElement accountManagement = driver.findElement(By.cssSelector(".dropdown-menu.dropdown-admin")); Assert.assertTrue(accountManagement.isDisplayed()); accountManagement.findElement(By.linkText("Account Management")).click(); Assert.assertEquals(driver.getTitle(), "List of Accounts"); WebElement accountsTable = driver.findElement(By.xpath("//div[@class='row well']/table")); Assert.assertTrue(accountsTable.isDisplayed()); WebElement addAccountBtn = driver.findElement(By.cssSelector(".btn.btn-primary")); System.out.println("Clicking on Add a new account button"); Assert.assertEquals(addAccountBtn.getText(), "Add a new Account"); addAccountBtn.click(); //Fill account add form WebElement accountForm = driver.findElement(By.tagName("form")); Assert.assertTrue(accountForm.isDisplayed()); System.out.println(accountForm.getAttribute("action")); accountForm.findElement(By.id("companyName")).sendKeys(formData.get(0)); accountForm.findElement(By.id("companyWebsite")).sendKeys(formData.get(1)); accountForm.findElement(By.id("adminName")).sendKeys(formData.get(2)); accountForm.findElement(By.id("adminEmail")).sendKeys(formData.get(3)); Select licenseType = new Select(driver.findElement(By.id("licenseType"))); licenseType.selectByVisibleText(formData.get(4)); Select services = new Select(driver.findElement(By.id("services"))); String requiredServices = formData.get(5); String multipleSel[] = formData.get(5).split(","); if (requiredServices.equalsIgnoreCase("All")) { services.selectByIndex(0); services.selectByIndex(1); services.selectByIndex(2); } else if (multipleSel.length > 1) { for (int i = 0; i < multipleSel.length; i++) services.selectByVisibleText(multipleSel[i]); } else services.selectByVisibleText(requiredServices); accountForm.findElement(By.id("companyName")).sendKeys(formData.get(5)); //submit the form System.out.println("Submitting the form"); accountForm.findElement(By.cssSelector("button[value='submit']")).click(); System.out.println("clicked on submit button"); accountsTable = driver.findElement(By.cssSelector("table.table-striped.table-hover.table-bordered")); Assert.assertTrue(accountsTable.isDisplayed()); System.out.println("form submitted sucessfully"); //Verify the presence of newly created account in the list of accounts System.out.println("Verifying if the newly created account is present in the list"); String tableData = accountsTable.getText(); System.out.println("Table Data: " + tableData); //findElement(By.xpath(".//*[@class='studyResultsId']/div/table/tbody/tr/td")).getText(); //Retrieving the data from the Td of table in to a string if (tableData.contains(formData.get(5))) { System.out.println("contains newly created account"); } else { System.out.println("does not contains newly created account"); } } else System.out.println("User not authorized to create an account"); }
From source file:com.mgmtp.jfunk.web.step.Check4ElementTest.java
License:Apache License
private void doTest(final boolean elementFound, final boolean mustExist) { By by = By.id("foo"); WebDriver webDriver = mock(WebDriver.class); if (elementFound) { WebElement webElement = mock(WebElement.class); when(webElement.isEnabled()).thenReturn(true); when(webElement.isDisplayed()).thenReturn(true); when(webDriver.findElements(by)).thenReturn(asList(webElement)); } else {//from w w w .j av a2s . c o m when(webDriver.findElements(by)).thenReturn(ImmutableList.<WebElement>of()); } Check4Element step = new Check4Element(by, mustExist); step.setWebDriver(webDriver); step.execute(); }
From source file:com.mgmtp.jfunk.web.step.JFunkWebElement.java
License:Apache License
/** * @throws StepException/*from w w w . j a v a 2 s .c om*/ * <ul> * <li>if element specified by {@link By} object in the constructor cannot be found</li> * <li>if a validation error occurred while checking the value of the WebElement * against the desired value</li> * </ul> */ @Override public void execute() throws StepException { elementValue = retrieveElementValue(); final WebDriverWait wait = new WebDriverWait(getWebDriver(), WebConstants.DEFAULT_TIMEOUT); final WebElement element = wait.until(new Function<WebDriver, WebElement>() { @Override public WebElement apply(final WebDriver input) { List<WebElement> webElements = input.findElements(by); if (webElements.isEmpty()) { throw new StepException("Could not find any matching element; By=" + by.toString()); } /* * If the search using the By object does find more than one matching element we are * looping through all elements if we find at least one which matches the criteria * below. If not, an exception is thrown. */ for (WebElement webElement : webElements) { if (webElement.isDisplayed()) { if (webElement.isEnabled() || !webElement.isEnabled() && (stepMode == StepMode.CHECK_DEFAULT || stepMode == StepMode.CHECK_VALUE)) { return webElement; } } } throw new StepException("All elements matching by=" + by + " were either invisible or disabled"); } }); switch (stepMode) { case CHECK_DEFAULT: // Check only for text input and textarea if (element.getTagName().equals(WebConstants.INPUT) && element.getAttribute(WebConstants.TYPE).equals(WebConstants.TEXT) || element.getTagName().equals(WebConstants.TEXTAREA)) { log.info(toString()); String value = element.getAttribute(WebConstants.VALUE); if (!DataUtils.isDefaultValue(value)) { throw new ValidationException("Wrong default value=" + value + " of " + this); } } break; case CHECK_VALUE: String checkValue = elementValue; if (checkTrafo != null) { checkValue = checkTrafo.trafo(checkValue); } log.info(this + ", checkValue=" + checkValue); if (element.getTagName().equalsIgnoreCase(WebConstants.SELECT)) { Select select = new Select(element); String value = select.getFirstSelectedOption().getAttribute(WebConstants.VALUE); if (!Objects.equal(checkValue, value)) { String text = select.getFirstSelectedOption().getText(); if (!Objects.equal(checkValue, text)) { throw new InvalidValueException(element, checkValue, text + " (option value=" + value + ")"); } } } else if (WebConstants.INPUT.equalsIgnoreCase(element.getTagName()) && WebConstants.RADIO.equals(element.getAttribute(WebConstants.TYPE))) { List<WebElement> elements = getWebDriver().findElements(by); for (WebElement webElement : elements) { if (webElement.isDisplayed() && webElement.isEnabled()) { String elVal = webElement.getAttribute(WebConstants.VALUE); if (elVal.equals(checkValue) && !webElement.isSelected()) { throw new InvalidValueException(element, checkValue, elVal); } } } } else if (WebConstants.CHECKBOX.equals(element.getAttribute(WebConstants.TYPE))) { boolean elVal = element.isSelected(); if (elVal != Boolean.valueOf(checkValue)) { throw new InvalidValueException(element, checkValue, String.valueOf(elVal)); } } else { String value = element.getAttribute(WebConstants.VALUE); if (!Objects.equal(checkValue, value)) { throw new InvalidValueException(element, checkValue, value); } } break; case SET_VALUE: String setValue = elementValue; if (setTrafo != null) { setValue = setTrafo.trafo(setValue); } log.info(this + (setTrafo != null ? ", setValue (after trafo)=" + setValue : "")); if (element.getTagName().equalsIgnoreCase(WebConstants.SELECT)) { Select select = new Select(element); // First check if a matching value can be found List<WebElement> options = select.getOptions(); boolean found = false; for (WebElement option : options) { String optionValue = option.getAttribute(WebConstants.VALUE); if (StringUtils.equals(optionValue, setValue)) { /* * WebElement with matching value could be found --> we are finished */ found = true; select.selectByValue(setValue); break; } } if (!found) { /* * Fallback: look for a WebElement with a matching visible text */ for (WebElement option : options) { String visibleText = option.getText(); if (StringUtils.equals(visibleText, setValue)) { /* * WebElement with matching value could be found --> we are finished */ found = true; select.selectByVisibleText(setValue); break; } } } if (!found) { throw new StepException( "Could not find a matching option element in " + element + " , By: " + by.toString()); } } else if (WebConstants.INPUT.equalsIgnoreCase(element.getTagName()) && WebConstants.RADIO.equals(element.getAttribute(WebConstants.TYPE))) { List<WebElement> elements = getWebDriver().findElements(by); for (WebElement webElement : elements) { if (webElement.isDisplayed() && webElement.isEnabled()) { String elVal = webElement.getAttribute(WebConstants.VALUE); if (elVal.equals(setValue) && !webElement.isSelected()) { webElement.click(); } } } } else if (WebConstants.CHECKBOX.equals(element.getAttribute(WebConstants.TYPE))) { if (Boolean.valueOf(setValue) && !element.isSelected() || !Boolean.valueOf(setValue) && element.isSelected()) { element.click(); } } else { if (element.isDisplayed() && element.isEnabled() && (element.getAttribute("readonly") == null || element.getAttribute("readonly").equals("false"))) { element.clear(); element.sendKeys(setValue); } else { log.warn("Element is invisible or disabled, value cannot be set"); } } break; case NONE: // do nothing break; default: throw new IllegalArgumentException("Unhandled StepMode=" + stepMode); } }
From source file:com.mgmtp.jfunk.web.util.WebElementFinder.java
License:Apache License
private void doFindElements(final List<WebElement> result, final WebDriver searchContext) { List<WebElement> elList = searchContext.findElements(by); for (WebElement element : elList) { if (!checkElementForList(element)) { continue; }//from ww w . j ava2 s.com if (condition != null && !condition.apply(element)) { continue; } result.add(element); } }
From source file:com.mx.santander.lh.obpyme.WebElement.ElementPageMarketingSantander.java
public List<WebElement> ListaURLBusqueda(WebDriver driver) { List<WebElement> listaURL = driver.findElements(By.className("r")); return listaURL; }
From source file:com.mycompany.mavenproject1.main.java
public static void main(String[] args) throws InterruptedException { String exePath = "C:\\Unit Testing\\Drivers\\chromedriver.exe"; Map<String, Object> prefs = new HashMap<String, Object>(); prefs.put("profile.default_content_setting_values.notifications", 2); ChromeOptions options = new ChromeOptions(); options.setExperimentalOption("prefs", prefs); System.setProperty("webdriver.chrome.driver", exePath); WebDriver driver = new ChromeDriver(options); JavascriptExecutor jse = (JavascriptExecutor) driver; WebDriverWait wait = new WebDriverWait(driver, 10); driver.get("https://www.facebook.com"); String actualTitle = driver.getTitle(); if (actualTitle.contentEquals("Facebook - Log In or Sign Up")) { driver.findElement(By.id("email")).sendKeys(""); driver.findElement(By.id("pass")).sendKeys(""); TimeUnit.SECONDS.sleep(1); driver.findElement(By.id("u_0_o")).submit(); System.out.println("Test Passed!"); } else {/*from www . java2 s . c o m*/ System.out.println("test is failed"); driver.close(); return; } int x = 0; while (x < 2) { jse.executeScript("scroll(0, 100000);"); x++; TimeUnit.SECONDS.sleep(1); } try { jse.executeScript("scroll(0, 0);"); List<WebElement> click = driver.findElements(By.xpath("//*[@class='comment_link _5yxe']")); List<WebElement> Names = driver.findElements(By.xpath("//*[@class=' UFICommentActorName']")); System.out.println(Names.size() + "This is how many elements in Names"); List<WebElement> comments = driver.findElements(By.xpath("//*[@class='UFICommentBody']")); for (WebElement el : click) { if (!el.getText().isEmpty()) { //System.out.println(el.getText()); System.out.println("Attempting to click " + el.getText()); jse.executeScript( "return arguments[0].scrollIntoView(0, document.documentElement.scrollHeight-10);", el); TimeUnit.MILLISECONDS.sleep(500); el.click(); } else { System.out.println("This is what we got from the web element\n"); System.out.println(el.getText()); } } jse.executeScript("int x = 0;" + "scroll(0, 0);"); TimeUnit.SECONDS.sleep(1); for (WebElement el : Names) { jse.executeScript( "return arguments[0].scrollIntoView(0, document.documentElement.scrollHeight-10);", el); TimeUnit.SECONDS.sleep(1); System.out.println(el.getText()); } } catch (NoSuchElementException e) { System.err.println("too slow on the scrolling"); } }
From source file:com.mycompany.seleniumtest.Selenium2Example.java
public static void main(String[] args) { // Create a new instance of the Firefox driver // Notice that the remainder of the code relies on the interface, // not the implementation. System.setProperty("webdriver.chrome.driver", "/Users/CosticaTeodor/Downloads/drivers/chromedriver"); System.setProperty("webdriver.safari.driver", "/usr/bin/safaridriver"); //WebDriver driver = new ChromeDriver(); WebDriver driver = new ChromeDriver(); // And now use this to visit the cars program driver.get("http://localhost:3000/"); // Alternatively the same thing can be done like this // driver.navigate().to("http://www.google.com"); //verify the page is loaded, wait 10 seconds if it doesn't try {//from w ww.j a va2 s . com driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS); System.out.println("Page loaded!"); } catch (Exception e) { System.err.println(e.getMessage()); System.err.println(e.getStackTrace()); } int rowCount = driver.findElements(By.xpath("//table[@class='table']/tbody/tr")).size(); if (rowCount == 5) { System.out.println(rowCount + " is the row count!"); } else { System.out.println("rowcount should be different!"); } // Find the filter input element by its name WebElement searchFilter = driver.findElement(By.id("filter")); // Enter 2002 to search for searchFilter.sendKeys("2002"); //check if there are two rows left rowCount = driver.findElements(By.xpath("//table[@class='table']/tbody/tr")).size(); System.out.println("Row count after filter is: " + rowCount); searchFilter.clear(); searchFilter.sendKeys(""); rowCount = driver.findElements(By.xpath("//table[@class='table']/tbody/tr")).size(); System.out.println("Row count after filter is: " + rowCount); //Close the browser driver.quit(); }
From source file:com.novartis.opensource.yada.test.YADAAdminTest.java
License:Apache License
/** * Test App Manager new query for new app then cancel * @throws InterruptedException if any thread has interrupted the current thread *//*from w w w .ja va2 s.c o m*/ @Test(dependsOnMethods = { "testAppCreation" }) public void testNewQueryForNewAppCancel() throws InterruptedException { WebDriver d = getDriver(); this.createQueryForNewApp("Test Cancel", "cancel"); new WebDriverWait(d, 20) .until(ExpectedConditions.invisibilityOfElementLocated(By.id("query-editor-container"))); Assert.assertEquals(d.findElements(By.cssSelector("#query-table tbody td.dataTables_empty")).size(), 1); }
From source file:com.novartis.opensource.yada.test.YADAAdminTest.java
License:Apache License
/** * Test App Manager new query for new app (prep only) * @throws InterruptedException if any thread has interrupted the current thread *//* w ww . j av a2 s.c om*/ @Test(dependsOnMethods = { "testNewQueryForNewAppCancel" }) public void testNewQueryForNewAppSave() throws InterruptedException { String qname = "Test Save"; this.createQueryForNewApp(qname, "save"); WebDriver d = getDriver(); // validate ui WebElement e = new WebDriverWait(d, 20) .until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(".alert-success"))); String expected = "Hooray! Query " + this.app + " " + qname + " was saved successfully."; Assert.assertEquals(e.getText(), expected); WebElement save = d.findElement(By.id("button-save")); Assert.assertFalse(save.isDisplayed()); // close dialog d.findElement(By.id("button-cancel")).click(); Thread.sleep(3000); // validate query table has rows Assert.assertEquals(d.findElements(By.cssSelector("#query-table tbody td.dataTables_empty")).size(), 0); List<WebElement> rows = d.findElements(By.cssSelector("#query-table tbody tr[role=\"row\"]")); Assert.assertNotEquals(Integer.valueOf(rows.size()), Integer.valueOf(0)); // validate content of query table List<WebElement> cells = d.findElements(By.cssSelector("#query-table tbody tr[role=\"row\"] td")); String expectedQname = this.app + " " + qname; String expectedComments = "Testing comments".substring(0, 12) + ""; boolean qnameMatches = false; boolean commentsMatches = false; for (WebElement cell : cells) { if (cell.getText().equals(expectedQname)) { qnameMatches = true; break; } } for (WebElement cell : cells) { if (cell.getText().equals(expectedComments)) { commentsMatches = true; break; } } Assert.assertTrue(qnameMatches && commentsMatches); }