List of usage examples for org.openqa.selenium WebDriver findElement
@Override WebElement findElement(By by);
From source file:ca.pe.cjsigouin.testinator.selenium.WebDriverMain.java
public static void main(String[] args) { System.setProperty("webdriver.gecko.driver", "/home/krystofurr/Programs/selenium/geckodriver"); System.setProperty("webdriver.chrome.driver", "/home/krystofurr/Programs/selenium/chromedriver"); // WebDriver driver = new FirefoxDriver(); WebDriver driver = new ChromeDriver(); // WebDriver driver = new InternetExplorerDriver(); //Puts an Implicit wait, Will wait for 10 seconds before throwing exception driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); //Launch website driver.navigate().to(CommonConstants.HOST + CommonConstants.URL_LOGIN); driver.findElement(By.id("emailAddress")).sendKeys("cjsigouin@gov.pe.ca"); driver.findElement(By.id("password")).sendKeys("Test12345!"); driver.findElement(By.id("loginButton")).click(); WebDriverWait wait = new WebDriverWait(driver, 5); wait.until(//from w ww . j a v a2 s . c o m ExpectedConditions.elementToBeClickable(By.xpath(".//*[@id='serviceWellSection']/div[2]/div/a/b"))); driver.get(CommonConstants.HOST + CommonConstants.URL_RESERVE_NAME_INTRO); WebDriverWait wait2 = new WebDriverWait(driver, 5); wait2.until(ExpectedConditions.elementToBeClickable(By.xpath(ReserveNameElement.INTRO_BUTTON_CANCEL))); driver.findElement(By.xpath(ReserveNameElement.INTRO_RADIO_RESERVE_NAME)).click(); // driver.findElement(By.xpath(ReserveNameElement.INTRO_SELECT_COMPANY_TYPE)).sendKeys("Incorp"); Select dropdown = new Select(driver.findElement(By.xpath(ReserveNameElement.INTRO_SELECT_COMPANY_TYPE))); dropdown.selectByVisibleText("Incorporated"); driver.findElement(By.xpath(ReserveNameElement.INTRO_BUTTON_NEXT)).click(); // WebDriver driver = new FirefoxDriver(); // LoginTester login = new LoginTester(driver); // IncorporatedTester tester = new IncorporatedTester(driver); // // login.start(); // //Maximize the browser // driver.manage().window().maximize(); // tester.start(); // tester.stop(); // // Click on Math Calculators // driver.findElement(By.xpath(".//*[@id='hcalc']/table/tbody/tr/td[2]/div[3]/a")).click(); // // // Click on Percent Calculators // driver.findElement(By.xpath(".//*[@id='content']/ul[1]/li[3]/a")).click(); // // // Enter value 10 in the first number of the percent Calculator // driver.findElement(By.id("cpar1")).sendKeys(data.getNumberText(2)); // // // Enter value 50 in the second number of the percent Calculator // driver.findElement(By.id("cpar2")).sendKeys(data.getNumberText(2)); // // // Click Calculate Button // driver.findElement(By.xpath(".//*[@id='content']/table[1]/tbody/tr[2]/td/input[2]")).click(); // // // // Get the Result Text based on its xpath // String result = driver.findElement(By.xpath(".//*[@id='content']/p[2]/font/b")).getText(); // // // // Print a Log In message to the screen // System.out.println(" The Result is " + result); //Close the Browser. driver.close(); }
From source file:calc.CalculatorUIT.java
public void testCodesCrud(DesiredCapabilities browser) throws Exception { ExtentReports logger = new ExtentReports("target//advancedReport.html", false); ExtentTest test1 = logger.startTest("Verify Target String"); ExtentTest test2 = logger.startTest("Verify Calculation Result"); WebDriver driver = null; System.out.println("Attempt connect to Selenium Node @ " + NodeURL); File pathToBinary = new File("/opt/firefox46/firefox/firefox-bin"); FirefoxBinary ffBinary = new FirefoxBinary(pathToBinary); FirefoxProfile firefoxProfile = new FirefoxProfile(); driver = new FirefoxDriver(ffBinary, firefoxProfile); try {/*w w w.j a v a 2 s.c om*/ System.out.println("attempt connect to target: " + TargetURL); driver.get(TargetURL); //input a addition 12+8 example in the calculator web-application; driver.findElement(By.xpath("(//input[@id='buttonRow'])[2]")).click(); driver.findElement(By.xpath("(//input[@id='buttonRow'])[3]")).click(); driver.findElement(By.xpath("(//input[@id='buttonRow'])[12]")).click(); driver.findElement(By.xpath("(//input[@id='buttonRow'])[10]")).click(); driver.findElement(By.xpath("(//input[@id='buttonRow'])[15]")).click(); //search target string value String targetStr = "Welcome to the Demo"; //verify result boolean isFound = (driver.findElement(By.tagName("body")).getText()).contains(targetStr); boolean result = driver.findElement(By.name("display")).getAttribute("value").contains("84"); //verify title if (isFound == true) { test1.log(LogStatus.PASS, "Title has been verified"); } if (isFound == false) { test1.log(LogStatus.FAIL, "Title has NOT been verified"); } //verify result if (result == true) { test2.log(LogStatus.PASS, "The Calculation result was correct: [12 multiply by 7 gave output of 84]"); } else { test2.log(LogStatus.FAIL, "The Calculation result was not correct [the title is[Welcome to the Demo!]"); } logger.endTest(test1); logger.endTest(test2); logger.flush(); System.out.println("look for= [" + targetStr + "]"); System.out.println("did we find it? [" + isFound + "]"); System.out.println("calculate 12 multiply by 7"); System.out.println("Was the result 84 ? [" + result + "]"); Assert.assertTrue(isFound); Assert.assertTrue(result); // Assert.assertEquals("hell",driver.getTitle()); //doTest(driver); // rest of test commands come here } catch (Exception e) { e.printStackTrace(); Assert.assertTrue(e.getMessage(), false); } finally { if (driver != null) { driver.quit(); } } }
From source file:cc.kune.selenium.PageObject.java
License:GNU Affero Public License
/** * Visibility of element located./*from w w w. java 2 s . co m*/ * * @param locator * the locator * @return the expected condition */ public ExpectedCondition<WebElement> visibilityOfElementLocated(final By locator) { return new ExpectedCondition<WebElement>() { @Override public WebElement apply(final WebDriver driver) { final WebElement toReturn = driver.findElement(locator); if (toReturn.isDisplayed()) { return toReturn; } return null; } }; }
From source file:ch.vorburger.vaadin.designer.tests.web.VaadinServerTest.java
License:Apache License
@Test @Ignore // TODO reactivate when http://dev.vaadin.com/ticket/9386 is fixed? public void testStartVaadinServer() throws Exception { VaadinServer server = new VaadinServer() { @Override//from www . jav a2 s .c o m protected Class<? extends Application> getVaadinApplicationClass() { return VaadinTestApplication.class; } }; try { server.start(); // Check if "Saluton!" button shows up: WebDriver driver = new InternetExplorerDriver(); driver.get(server.getURL()); WebElement button = driver.findElement(By.id(HTML_ID)); String text = button.getText(); Assert.assertEquals("Saluton!", text); driver.quit(); } finally { server.stop(); } }
From source file:cn.edu.hfut.dmic.webcollector.example.FirefoxSelenium3.java
License:Open Source License
public static void main(String[] args) throws Exception { Executor executor = new Executor() { @Override/*w ww. j a va2s . 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("attend_rate")) { db.getCollection(s).drop(); } } DBCollection dbCollection = db.getCollection("attend_rate"); ProfilesIni pi = new ProfilesIni(); FirefoxProfile profile = pi.getProfile("default"); WebDriver driver = new FirefoxDriver(profile); driver.manage().window().maximize(); driver.manage().timeouts().pageLoadTimeout(3, TimeUnit.SECONDS); // driver.setJavascriptEnabled(false); driver.get(datum.getUrl()); // System.out.println(driver.getPageSource()); driver.findElement(By.xpath("//*[@id='seat_city']")).click(); driver.switchTo().window(driver.getWindowHandle()); int city_num = driver.findElements(By.xpath("//div[@id='all-citys']/div/ul/li/a")).size(); for (int i = 0; i < city_num; i++) { System.out.println("A city chosen" + i); System.out.println( driver.findElements(By.xpath("//div[@id='all-citys']/div/ul/li/a")).get(i).getText()); String city = driver.findElements(By.xpath("//div[@id='all-citys']/div/ul/li/a")).get(i) .getText(); ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", driver.findElements(By.xpath("//div[@id='all-citys']/div/ul/li/a")).get(i)); ((JavascriptExecutor) driver).executeScript("window.scrollBy(0, -250)", ""); Thread.sleep(1000); new Actions(driver) .moveToElement( driver.findElements(By.xpath("//div[@id='all-citys']/div/ul/li/a")).get(i)) .click().perform(); driver.switchTo().window(driver.getWindowHandle()); // System.out.println(driver.findElement(By.xpath("//span[@class='today']/em")).getText()); System.out.println(driver.findElement(By.xpath("//span[@class='today']")).getText()); for (int j = 0; j < driver .findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c1 lineDot']")) .size(); j++) { System.out.println(driver .findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c1 lineDot']")) .get(j).getText()); System.out.println( driver.findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c2 red']")) .get(j).getText()); System.out.println( driver.findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c3 gray']")) .get(j).getText()); BasicDBObject dbObject = new BasicDBObject(); dbObject.append("title", driver.findElement(By.xpath("//span[@class='today']")).getText()) .append("city", city) .append("mov_cnname", driver.findElements( By.xpath("//div[@id='seat_table']//ul//li[@class='c1 lineDot']")) .get(j).getText()) .append("boxoffice_rate", driver .findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c2 red']")) .get(j).getText()) .append("visit_pershow", driver .findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c3 gray']")) .get(j).getText()); dbCollection.insert(dbObject); } System.out.println("new city list to choose"); new Actions(driver).moveToElement(driver.findElement(By.xpath("//*[@id='seat_city']"))).click() .perform(); driver.switchTo().window(driver.getWindowHandle()); Thread.sleep(500); } driver.close(); driver.quit(); mongoClient.close(); } }; //DBDBManager DBManager manager = new BerkeleyDBManager("crawl"); //Crawler?DBManagerExecutor Crawler crawler = new Crawler(manager, executor); crawler.addSeed("http://pf.maoyan.com/attend/rate"); crawler.start(1); }
From source file:cn.edu.hfut.dmic.webcollector.example.FirefoxSelenium4.java
License:Open Source License
public static void main(String[] args) throws Exception { Executor executor = new Executor() { @Override//www . j a va 2 s.com 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("rankings_am")) { db.getCollection(s).drop(); } } DBCollection dbCollection = db.getCollection("attend_rate"); ProfilesIni pi = new ProfilesIni(); FirefoxProfile profile = pi.getProfile("default"); WebDriver driver = new FirefoxDriver(profile); driver.manage().timeouts().pageLoadTimeout(3, TimeUnit.SECONDS); // driver.setJavascriptEnabled(false); driver.get(datum.getUrl()); // System.out.println(driver.getPageSource()); List<WebElement> movie_name = driver .findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c1 lineDot']")); List<WebElement> boxoffice_rate = driver .findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c2 red']")); List<WebElement> visit_pershow = driver .findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c3 gray']")); WebElement title = driver.findElement(By.xpath("//span[@class='today']/em")); WebElement title2 = driver.findElement(By.xpath("//span[@class='today']")); System.out.println(title.getText()); System.out.println(title.getText()); for (int i = 0; i < movie_name.size(); i++) { System.out.println(movie_name.get(i).getText()); System.out.println(boxoffice_rate.get(i).getText()); System.out.println(visit_pershow.get(i).getText()); // BasicDBObject dbObject = new BasicDBObject(); // dbObject.append("title", title).append("rank", amList.get(0)).append("mov_cnname", cn_name).append("mov_enname", en_name).append("toweek_rev", amList.get(2)).append("total_rev", amList.get(3)).append("val_week", amList.get(4)); // dbCollection.insert(dbObject); } driver.quit(); } }; //DBDBManager DBManager manager = new BerkeleyDBManager("crawl"); //Crawler?DBManagerExecutor Crawler crawler = new Crawler(manager, executor); crawler.addSeed("http://pf.maoyan.com/attend/rate"); crawler.start(1); }
From source file:cn.newtouch.util.test.utils.SeleniumUtils.java
License:Apache License
/** * Selnium1.0.//from w w w. j ava2 s . c o m */ public static boolean isTextPresent(WebDriver driver, String text) { return StringUtils.contains(driver.findElement(By.tagName("body")).getText(), text); }
From source file:co.edu.icesi.i2t.slrtools.bib.transformations.TransformBibACM.java
License:Open Source License
/** * Funcion principal para la transformacion de los archivos html en un solo * arhivo consolidado BIB, la funcion se encarga de extraer del html cada * link de articulo, despues de tener el listado de url se dispone con la * ayuda de selenium webdriver el ingreso a cada url y descargar el BIBtex * para finalizar con la union de todos en un solo archivo BIB * * @param sourceFilesPath String con la ruta de la carpeta donde se * encuentran los archivos html a transformas * @param targetFilePath String con la ruta fisica del directorio donde se * guardara el archivo consolodidao/*w ww .j a va 2 s . co m*/ * @param targetFileName */ public static boolean transformFiles(String sourceFilesPath, String targetFilePath, String targetFileName) { boolean bibFileCreated = false; System.out.println(""); System.out.println("-----------------------------"); System.out.println("Generating BibTeX for ACM Digital Library results..."); System.out.println(""); String bibContent = ""; List<String> urls = extractURL(sourceFilesPath); FirefoxProfile profile = new FirefoxProfile(); WebDriver webDriver = new FirefoxDriver(profile); for (int i = 0; i < urls.size(); i++) { try { System.out.println("[INFO] Retrieving BibTeX from URL: " + urls.get(i)); String idFile = urls.get(i).split("id=")[1].split("&")[0]; idFile = idFile.substring(idFile.indexOf(".") + 1, idFile.length()); String url = (urls.get(i)); webDriver.get(url); WebElement bibField = (new WebDriverWait(webDriver, 10)) .until(ExpectedConditions.presenceOfElementLocated(By.linkText("BibTeX"))); try { Thread.sleep(2000); } catch (InterruptedException e) { } bibField.click(); WebElement textBib = (new WebDriverWait(webDriver, 10)) .until(ExpectedConditions.presenceOfElementLocated(By.id(idFile))); String reference = textBib.getText(); String referenceAbstract = webDriver.findElement(By.id("abstract")).getText(); referenceAbstract = "abstract = {" + referenceAbstract + "}}" + System.lineSeparator(); bibContent += reference.substring(0, reference.length() - 2) + referenceAbstract; //Thread.sleep(10000); //tempurl.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); } catch (TimeoutException e) { System.out.println( "[ERROR] Failed to retrieve BibTex. The application may have been blocked by ACM Digital Library. Try again later."); } catch (Exception e) { System.out.println("[ERROR] Failed to retrieve BibTeX. " + e.getMessage()); } } webDriver.quit(); try { saveBibFile(bibContent, targetFilePath, targetFileName); if (!bibContent.equals("")) { bibFileCreated = true; } } catch (Exception e) { System.out.println("[ERROR] Failed to create BibTeX file." + e.getMessage()); } System.out.println("-----------------------------"); return bibFileCreated; }
From source file:co.edu.icesi.i2t.slrtools.webdrivers.WebDriverACM.java
License:Open Source License
/** * Funcion que se encarga de realizar automaticamente la busqueda en la base * de datos ACM Digital Library conforme a una cadena de busqueda * introducida, ACM digital library no permite la descarga de ningun archivo * del resultado de la busqueda, por tal razn, se descarga el codigo fuente * de la pagina en el source del proyecto el cual posteriormente es usado * para la extraccin de la informacin y construccion del BIB con los * resultados obtenidos/* www. j av a 2s.c o m*/ * * @param searchStrings este parametro es la cadena de busqueda que retorna * la funcion mixACM#mixWords2, cada cadena de busqueda esta separada por ; * @param url este paremetro es el URL de la busqueda avanzada de ACM * Digital Library * @see mixWords.mixACM#mixWords2(java.lang.String, java.lang.String) */ public static void searchWeb(String searchStrings, String url) { /* a esta funcion se debe mejorar * 1: validar el boton siguiente sin try catch, mejorar el manejo de las expeciones */ System.out.println(""); System.out.println("-----------------------------"); System.out.println("Searching ACM Digital Library..."); System.out.println("Search strings: " + searchStrings + ""); System.out.println(""); FirefoxProfile profile = new FirefoxProfile(); WebDriver webDriver = new FirefoxDriver(profile); String[] strings = searchStrings.split(";"); for (int i = 0; i < strings.length; i++) { try { webDriver.get(url); WebElement searchField = webDriver.findElement(By.name("within")); searchField.click(); searchField.sendKeys(strings[i]); WebElement buttonSearch = webDriver.findElement(By.name("Go")); buttonSearch.click(); List<WebElement> stringResult = webDriver .findElements(By.xpath("//span[contains(@style, 'background-color:yellow')]")); if (!stringResult.isEmpty()) { System.out.println( "[WARNING] Search string " + (i + 1) + ": " + strings[i] + " retrieves no results"); } else { int counter = 1; try { WebElement nextField = null; do { String sourceCode = webDriver.getPageSource(); File targetDirectory = new File("files" + File.separator + Database.ACM.getName()); targetDirectory.mkdir(); try (PrintWriter file = new PrintWriter( "files" + File.separator + Database.ACM.getName() + File.separator + "searchResults_" + i + "_" + counter + ".html", "UTF-8")) { file.print(sourceCode); } nextField = (new WebDriverWait(webDriver, 10)) .until(ExpectedConditions.presenceOfElementLocated(By.linkText("next"))); try { Thread.sleep(10000); } catch (InterruptedException e) { } nextField.click(); counter++; } while (true); } catch (NoSuchElementException | TimeoutException | NullPointerException e) { System.out.println("[INFO] Search string " + (i + 1) + ": " + strings[i] + " has " + counter + (counter == 1 ? " result" : " results") + "returned"); } } } catch (FileNotFoundException | UnsupportedEncodingException e) { System.out.println( "[ERROR] Search string " + (i + 1) + ": " + strings[i] + " failed. " + e.getMessage()); } catch (NoSuchElementException e) { System.out.println( "[ERROR] The application has been blocked by ACM Digital Library. Try again later."); } try { Thread.sleep(10000); } catch (InterruptedException e) { } } webDriver.quit(); System.out.println("[INFO] Finished search in ACM Digital Library"); System.out.println("-----------------------------"); }
From source file:co.edu.icesi.i2t.slrtools.webdrivers.WebDriverIEEEComputerScience.java
License:Open Source License
/** * /*from w w w . jav a2 s .c om*/ * @param cadenasBusqueda * @param direccionBusqueda */ public static void searchWeb(String cadenasBusqueda, String direccionBusqueda) { /* a esta funcion se debe mejorar * 1: automatizar las preferencias para la descarga automatica * 2: la ruta de descarga * 3: el cierre del navegador al finalizar la ultima descarga*/ System.out.println("----------inicia busqueda web IEEE Computer Society----------"); System.out.println("Cadena de palabras a buscar: " + cadenasBusqueda); System.out.println("------------------------------------------------------"); FirefoxProfile profile = new FirefoxProfile(); WebDriver url = new FirefoxDriver(profile); String[] lcadenasBusqueda = cadenasBusqueda.split(";"); for (int i = 0; i < lcadenasBusqueda.length; i++) { try { url.get(direccionBusqueda); WebElement searchField = url.findElement(By.name("queryText1")); WebElement buttonSearch = url.findElement(By.id("searchButton")); searchField.click(); searchField.sendKeys(lcadenasBusqueda[i]); buttonSearch.click(); WebElement selectField = url.findElement(By.id("select1")); WebElement buttonField = url.findElement(By.id("form1Button")); selectField.sendKeys("100"); buttonField.click(); try { WebElement stringResult = url .findElement(By.xpath("//div[contains(@class, 'searchwhitebox')]")); System.out.println("Busqueda: " + i + " cadena de busqueda:" + lcadenasBusqueda[i] + " - " + stringResult.getText()); //String sourceCode=url.getPageSource(); //PrintWriter archivo = new PrintWriter("busquedasIEEECS/"+lcadenasBusqueda[i]+".html", "UTF-8"); //archivo.print(sourceCode); //archivo.close(); } catch (Exception e) { System.out.println("[OJO]" + " Busqueda: " + i + " la cadena de busqueda: " + lcadenasBusqueda[i] + " no trae resultados"); } } catch (Exception e) { System.out .println("excepcion busqueda cadena: " + lcadenasBusqueda[i] + " , motivo excepcion: " + e); } } //url.quit(); System.out.println("----------fin busqueda web IEEE Computer Society----------"); }