本文转自:http://www.programcreek.com/java-api-examples/index.php?api=org.openqa.selenium.support.ui.FluentWait

java代码实例org.openqa.selenium.support.ui.fluentwait
以下是票数最高的例子展示了如何使用org.openqa.selenium.support.ui.fluentwait。这些示例是从开放源代码项目中提取的。

Example 1
Project: abmash   File: WaitFor.java View source code   7 votes vote down vote up
/*** Waits until element is found. Useful for waiting for an AJAX call to complete.* * @param query the element query* @throws TimeoutException*/public void query(Query query) throws TimeoutException {
//      WebDriverWait wait = new WebDriverWait(browser.getWebDriver(), timeout);FluentWait<WebDriver> wait = new FluentWait<WebDriver>(browser.getWebDriver()).withTimeout(timeout, TimeUnit.SECONDS).pollingEvery(500, TimeUnit.MILLISECONDS);// start waiting for given elementwait.until(new ElementWaitCondition(browser, query));}Example 2
Project: seauto   File: HtmlView.java View source code  7 votes vote down vote up
/*** Waits for an element to appear on the page before returning. Example:* WebElement waitElement =* fluentWait(By.cssSelector(div[class='someClass']));* * @param locator* @return*/
protected WebElement waitForElementToAppear(final By locator)
{Wait<WebDriver> wait = new FluentWait<WebDriver>(webDriver).withTimeout(30, TimeUnit.SECONDS).pollingEvery(5, TimeUnit.SECONDS).ignoring(NoSuchElementException.class);WebElement element = null;try {element = wait.until(new Function<WebDriver, WebElement>() {@Overridepublic WebElement apply(WebDriver driver){return driver.findElement(locator);}});}catch (TimeoutException e) {try {// I want the error message on what element was not foundwebDriver.findElement(locator);}catch (NoSuchElementException renamedErrorOutput) {// print that error messagerenamedErrorOutput.addSuppressed(e);// throw new// NoSuchElementException("Timeout reached when waiting for element to be found!"// + e.getMessage(), correctErrorOutput);throw renamedErrorOutput;}e.addSuppressed(e);throw new NoSuchElementException("Timeout reached when searching for element!", e);}return element;
}Example 3
Project: records-management   File: BrowseList.java View source code    7 votes vote down vote up
/*** Wait for all the expected rows to be there*/
private void waitForRows()
{// get the number of expected itemsint itemCount = getItemCount();if (itemCount != 0){// wait predicatePredicate<WebDriver> waitForRows = (w) ->{List<WebElement> rows = w.findElements(rowsSelector);return (itemCount == rows.size());};// wait until we have the expected number of rowsnew FluentWait<WebDriver>(Utils.getWebDriver()).withTimeout(10, TimeUnit.SECONDS).pollingEvery(1, TimeUnit.SECONDS).until(waitForRows); }
}Example 4
Project: automation-test-engine   File: AbstractElementFind.java View source code   6 votes vote down vote up
/*** Creates the wait.** @param driver*            the driver*/
public void createWait(WebDriver driver) {wait = new FluentWait<WebDriver>(driver).withTimeout(30, TimeUnit.SECONDS).pollingEvery(5, TimeUnit.SECONDS).ignoring(NoSuchElementException.class);
}Example 5
Project: thucydides   File: WhenTakingLargeScreenshots.java View source code    6 votes vote down vote up
private void waitUntilFileIsWritten(File screenshotFile) {Wait<File> wait = new FluentWait<File>(screenshotFile).withTimeout(10, TimeUnit.SECONDS).pollingEvery(250, TimeUnit.MILLISECONDS);wait.until(new Function<File, Boolean>() {public Boolean apply(File file) {return file.exists();}});
}Example 6
Project: vaadin-for-heroku   File: SessionTestPage.java View source code    6 votes vote down vote up
public SessionTestPage(final WebDriver driver) {this.driver = driver;wait = new FluentWait<WebDriver>(driver).withTimeout(1, TimeUnit.SECONDS).ignoring(NoSuchElementException.class,ElementNotFoundException.class);}Example 7
Project: seleniumQuery   File: SeleniumQueryFluentWait.java View source code    6 votes vote down vote up
/*** @since 0.9.0*/
private <T> T fluentWait(SeleniumQueryObject seleniumQueryObject, Function<By, T> function, String reason) {try {return new FluentWait<>(seleniumQueryObject.getBy()).withTimeout(waitUntilTimeout, TimeUnit.MILLISECONDS).pollingEvery(waitUntilPollingInterval, TimeUnit.MILLISECONDS).ignoring(StaleElementReferenceException.class).ignoring(NoSuchElementException.class).until(function);} catch (TimeoutException sourceException) {throw new SeleniumQueryTimeoutException(sourceException, seleniumQueryObject, reason);}
}Example 8
Project: objectfabric   File: Selenium.java View source code    6 votes vote down vote up
private WebElement fluentWait(final By locator) {Wait<WebDriver> wait = new FluentWait<WebDriver>(_driver) //.withTimeout(5, TimeUnit.SECONDS) //.pollingEvery(100, TimeUnit.MILLISECONDS) //.ignoring(NoSuchElementException.class);WebElement foo = wait.until(new Function<WebDriver, WebElement>() {public WebElement apply(WebDriver driver) {return driver.findElement(locator);}});return foo;
}Example 9
Project: redsniff   File: RedsniffWebDriverTester.java View source code 6 votes vote down vote up
/*** Wait until the supplied {@link FindingExpectation} becomes satisfied, or throw a {@link TimeoutException}* , using the supplied {@link FluentWait} * This should only be done using a wait obtained by calling {@link #waiting()} to ensure the correct arguments are passed.* * @param expectation* @param wait* @return*/
public <T, E, Q extends TypedQuantity<E, T>> T waitFor(final FindingExpectation<E, Q, SearchContext> expectation, FluentWait<WebDriver> wait) {try {return new Waiter(wait).waitFor(expectation);}catch(FindingExpectationTimeoutException e){//do a final check to get the message unoptimizedExpectationCheckResult<E, Q> resultOfChecking = checker.resultOfChecking(expectation);String reason;if(resultOfChecking.meetsExpectation())reason = "Expectation met only just after timeout.  At timeout was:\n" + e.getReason();else {reason = resultOfChecking.toString();//if still not found first check there isn't a page error or somethingdefaultingChecker().assertNoUltimateCauseWhile(newDescription().appendText("expecting ").appendDescriptionOf(expectation));}throw new FindingExpectationTimeoutException(e.getOriginalMessage(), reason, e);}
}Example 10
Project: yatol   File: AbstractWebFixture.java View source code 6 votes vote down vote up
/*** Searches for a given text on the page.* * @param text*            to be searched for* @return {@code true} if the {@code text} is present on the page,*         {@code false} otherwise*/
public boolean checkTextIsPresentOnPage(final String text) {// waitForPage();try {int interval = (int) Math.floor(Math.sqrt(timeout));Wait<WebDriver> wait = new FluentWait<WebDriver>(webDriver).withTimeout(timeout, TimeUnit.SECONDS).pollingEvery(interval, TimeUnit.SECONDS).ignoring(NoSuchElementException.class, StaleElementReferenceException.class);return wait.until(new ExpectedCondition<Boolean>() {@Overridepublic Boolean apply(WebDriver driver) {String source = webDriver.getPageSource();source = source.replaceFirst("(?i:<HEAD[^>]*>[\\s\\S]*</HEAD>)", "");return source.contains(text.trim());}});} catch (Exception e) {return false;}
}Example 11
Project: seleniumcapsules   File: TicketflyTest.java View source code   6 votes vote down vote up
@Test
public void changeLocationUsingExplicitWaitLambda() {WebDriver driver = new ChromeDriver();driver.get("http://www.ticketfly.com");driver.findElement(linkText("change location")).click();WebDriverWait webDriverWait = new WebDriverWait(driver, 5);WebElement location = webDriverWait.until(new Function<WebDriver, WebElement>() {@Overridepublic WebElement apply(WebDriver driver) {return driver.findElement(By.id("location"));}});FluentWait<WebElement> webElementWait= new FluentWait<WebElement>(location).withTimeout(30, SECONDS).ignoring(NoSuchElementException.class);WebElement canada = webElementWait.until(new Function<WebElement, WebElement>() {@Overridepublic WebElement apply(WebElement element) {return location.findElement(linkText("CANADA"));}});canada.click();WebElement allCanada = webElementWait.until(new Function<WebElement, WebElement>() {@Overridepublic WebElement apply(WebElement element) {return location.findElement(linkText("Ontario"));}});allCanada.click();assertEquals(0, driver.findElements(linkText("Ontario")).size());assertEquals("Ontario", driver.findElement(By.xpath("//div[@class='tools']/descendant::strong")).getText());
}Example 12
Project: nuxeo-distribution   File: Select2WidgetElement.java View source code  6 votes vote down vote up
/*** Do a wait on the select2 field.** @throws TimeoutException** @since 6.0*/
private void waitSelect2()throws TimeoutException {Wait<WebElement> wait = new FluentWait<WebElement>(!mutliple ? driver.findElement(By.xpath(S2_SINGLE_INPUT_XPATH)): element.findElement(By.xpath(S2_MULTIPLE_INPUT_XPATH))).withTimeout(SELECT2_LOADING_TIMEOUT,TimeUnit.SECONDS).pollingEvery(100,TimeUnit.MILLISECONDS).ignoring(NoSuchElementException.class);Function<WebElement, Boolean> s2WaitFunction = new Select2Wait();wait.until(s2WaitFunction);
}Example 13
Project: gxt-driver   File: Tree.java View source code  6 votes vote down vote up
public void waitForLoaded(long duration, TimeUnit unit) {new FluentWait<WebDriver>(getDriver()).withTimeout(duration, unit).ignoring(NotFoundException.class).until(new Predicate<WebDriver>() {@Overridepublic boolean apply(WebDriver input) {return !methods.isLoading(getWidgetElement(), getElement());}});
}Example 14
Project: gwt-driver   File: GwtWidgetFinder.java View source code   6 votes vote down vote up
public W waitFor(long duration, TimeUnit unit) {return new FluentWait<WebDriver>(driver).withTimeout(duration, unit).ignoring(NotFoundException.class).until(new Function<WebDriver, W>() {@Overridepublic W apply(WebDriver webDriver) {return done();}});
}Example 15
Project: nuxeo   File: Select2WidgetElement.java View source code   6 votes vote down vote up
/*** Do a wait on the select2 field.** @throws TimeoutException* @since 6.0*/
private void waitSelect2() throws TimeoutException {Wait<WebElement> wait = new FluentWait<WebElement>(!mutliple ? driver.findElement(By.xpath(S2_SINGLE_INPUT_XPATH)): element.findElement(By.xpath(S2_MULTIPLE_INPUT_XPATH))).withTimeout(SELECT2_LOADING_TIMEOUT,TimeUnit.SECONDS).pollingEvery(100, TimeUnit.MILLISECONDS).ignoring(NoSuchElementException.class);Function<WebElement, Boolean> s2WaitFunction = new Select2Wait();wait.until(s2WaitFunction);
}Example 16
Project: selenium-addon   File: SeleniumActions.java View source code   6 votes vote down vote up
/*** Clicks the button located at the given table at the given row and column. It additionally expects it to be secured with a* ConfirmDia?og (https://vaadin.com/directory#addon/confirmdialog).*/
public void clickTableButtonWithConfirmation(String tableName, int row, int col) {clickTableButton(tableName, row, col);ConfirmDialogPO popUpWindowPO = new ConfirmDialogPO(driver);popUpWindowPO.clickOKButton();FluentWait<WebDriver> wait = new WebDriverWait(driver, WaitConditions.LONG_WAIT_SEC, WaitConditions.SHORT_SLEEP_MS).ignoring(StaleElementReferenceException.class);wait.until(new ExpectedCondition<Boolean>() {@Overridepublic Boolean apply(WebDriver driver) {List<WebElement> findElements = driver.findElements(By.xpath("//div[contains(@class, 'v-window ')]"));return findElements.size() == 0;}});WaitConditions.waitForShortTime();
}Example 17
Project: constellation   File: CstlClientTestCase.java View source code 5 votes vote down vote up
/*** test wms creation page navigation*/
//    @Test
//    @RunAsClientpublic void testCreateWMS() {driver.get(deploymentURL.toString() + "webservices");WebElement createService = driver.findElement(By.id("createservice"));assertNotNull(createService);//wms button test visibilityWebElement wmschoice = driver.findElement(By.id("wmschoice"));assertFalse(wmschoice.isDisplayed());createService.click();assertTrue(wmschoice.isDisplayed());//go to form first pagewmschoice.click();//Test visibility parts.WebElement description = driver.findElement(By.id("description"));final WebElement metadata = driver.findElement(By.id("metadata"));Wait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(30, TimeUnit.SECONDS).pollingEvery(5, TimeUnit.SECONDS).ignoring(NoSuchElementException.class);wait.until(new Function<WebDriver, Boolean>() {@Overridepublic Boolean apply(org.openqa.selenium.WebDriver webDriver) {return metadata.isDisplayed()==false;}});assertTrue(description.isDisplayed());assertFalse(metadata.isDisplayed());//add forms dataWebElement createtionWmsForm = driver.findElement(By.tagName("form"));createtionWmsForm.findElement(By.id("name")).sendKeys("serviceName");createtionWmsForm.findElement(By.id("identifier")).sendKeys("serviceIdentifier");createtionWmsForm.findElement(By.id("keywords")).sendKeys("service keywords");createtionWmsForm.findElement(By.id("inputDescription")).sendKeys("service Description");createtionWmsForm.findElement(By.id("inputDescription")).sendKeys("service Description");createtionWmsForm.findElement(By.id("v130")).click();driver.findElement(By.id("nextButton")).click();new WebDriverWait(driver, 20).until(new ExpectedCondition<Object>() {@Overridepublic Object apply(org.openqa.selenium.WebDriver webDriver) {if(webDriver.findElement(By.id("contactName")).isDisplayed())return webDriver.findElement(By.id("contactName"));else return null;}});// contact information & addresscreatetionWmsForm.findElement(By.id("contactName")).sendKeys("contact Name");createtionWmsForm.findElement(By.id("contactOrganisation")).sendKeys("contact Organisation");createtionWmsForm.findElement(By.id("contactPosition")).sendKeys("contact position");createtionWmsForm.findElement(By.id("contactPhone")).sendKeys("contact Phone");createtionWmsForm.findElement(By.id("contactFax")).sendKeys("contact Fax");createtionWmsForm.findElement(By.id("contactEmail")).sendKeys("contact eMail");createtionWmsForm.findElement(By.id("contactAddress")).sendKeys("contact Adress");createtionWmsForm.findElement(By.id("contactCity")).sendKeys("contact City");createtionWmsForm.findElement(By.id("contactState")).sendKeys("contact State");createtionWmsForm.findElement(By.id("contactPostcode")).sendKeys("contact PostCode");createtionWmsForm.findElement(By.id("contactCountry")).sendKeys("contact Country");//constraintcreatetionWmsForm.findElement(By.id("fees")).sendKeys("fees");createtionWmsForm.findElement(By.id("accessConstraints")).sendKeys("access Constraint");createtionWmsForm.findElement(By.id("layerLimit")).sendKeys("layer Limit");createtionWmsForm.findElement(By.id("maxWidth")).sendKeys("max Width");createtionWmsForm.findElement(By.id("maxHeight")).sendKeys("max Height");createtionWmsForm.submit();}Example 18
Project: NYU-Bobst-Library-Reservation-Automator-Java   File: Automator.java View source code   5 votes vote down vote up
/*** Main function to run the Automator* @param args Allows 1 argument for the file name of the user logins in .csv format*/
public static void main(String[] args)
{// Turns off annoying htmlunit warningsjava.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(java.util.logging.Level.OFF);// Setting inheritance stuffProperties settings = new Properties();InputStream input = null;// Settings variables to be changedint timeDelta = 90;String description = "NYU Phi Kappa Sigma Study Session";String floorNumber = "LL1";String roomNumber = "20";String userLoginsFilePath = "userLogins.csv";try{input = new FileInputStream("settings");settings.load(input);// Initializes each value from the defaults to the values in the settings filetimeDelta = Integer.parseInt(settings.getProperty("timeDelta"));description = settings.getProperty("description");floorNumber = settings.getProperty("floorNumber");roomNumber = settings.getProperty("roomNumber");userLoginsFilePath = settings.getProperty("userLoginFile");}catch (IOException ex){System.err.println("Settings file could not be read correctly");}finally{if (input != null){try{input.close();}catch (IOException e){System.err.println("Error trying to close stream from settings file");}}}// Gets the reservation date only once at the startLocalDate currentDate = LocalDate.now();LocalDate reservationDate = currentDate.plusDays(timeDelta);// Date in string formatString reservationYear = Integer.toString(reservationDate.getYear());String reservationMonth = "";try{reservationMonth = toMonth(Integer.toString(reservationDate.getMonthValue()));}catch (MonthException e){System.out.println(e.getMessage());}String reservationDay = Integer.toString(reservationDate.getDayOfMonth());// Logging capability stuffFile logs = null;// Error loggingPrintStream pErr = null;FileOutputStream fErr = null;File errors = null;// Status loggingPrintStream pOut = null;FileOutputStream fOut = null;File status = null;try{// Creates the directory hierarchylogs = new File("logs");if (!logs.isDirectory())logs.mkdir();status = new File("logs/status");if (!status.isDirectory())status.mkdir();errors = new File("logs/errors");if (!errors.isDirectory())errors.mkdir();fOut = new FileOutputStream("logs/status/" + reservationDate.toString() + ".status");fErr = new FileOutputStream("logs/errors/" + reservationDate.toString() + ".err");pOut = new PrintStream(fOut);pErr = new PrintStream(fErr);System.setOut(pOut);System.setErr(pErr);}catch (FileNotFoundException ex){System.err.println("Couldn't find the logging file");}// Checks for user logins .csv file existenceFile userLogins = new File(userLoginsFilePath);try{if (!userLogins.exists() || (userLogins.isDirectory()))throw new IOException("userLogins.csv does not exist, or is a directory");}catch (IOException e){System.err.println(e.getMessage());}// Builds an array of users based off of .csv// Opens file streamFileReader fr = null;BufferedReader br = null;StringTokenizer st = null;ArrayList<User> users = new ArrayList<User>();try {fr = new FileReader(userLogins);br = new BufferedReader(fr);boolean lineSkip = true;for (String line; (line = br.readLine()) != null; ){if (lineSkip)lineSkip = false;else{boolean timestampSkip = true;st = new StringTokenizer(line, ",");while (st.hasMoreTokens()){// Advances past the timeStampif (timestampSkip){timestampSkip = false;st.nextToken();}else{String username = st.nextToken();String password = st.nextToken();// Advances past the years until graduationwhile (st.hasMoreTokens())st.nextToken();users.add(new User(username, password));}} // End of while loop} // End of else} // End of the for loop} // End of the try blockcatch (IOException e1){System.err.println("File could not be found");}finally{try{fr.close();br.close();}catch (IOException e){System.err.println("File error while trying to close file");}}// Start of going through the registration with each userfor (int i = 0; i < users.size(); ++i){// Resets the AM at the end of the loop, since it's a static variableAM_PM = true;// Builds a browser connectionWebDriver browser = new FirefoxDriver();browser.manage().window().maximize();//HtmlUnitDriver browser = new HtmlUnitDriver(BrowserVersion.CHROME);//browser.setJavascriptEnabled(true);try{// Starts automation for userSystem.out.println("User number: " + i + " status: starting");browser.get("https://login.library.nyu.edu/pds?func=load-login&institute=NYU&calling_system=https:"+ "login.library.nyu.edu&url=https%3A%2F%2Frooms.library.nyu.edu%2Fvalidate%3Freturn_url%3Dhttps"+ "%253A%252F%252Frooms.library.nyu.edu%252F%26https%3A%2F%2Flogin.library.nyu.edu_action%3Dnew%2"+ "6https%3A%2F%2Flogin.library.nyu.edu_controller%3Duser_sessions");// Sleep until the div we want is visible or 15 seconds is overFluentWait<WebDriver> fluentWait = new FluentWait<WebDriver>(browser).withTimeout(20, TimeUnit.SECONDS).pollingEvery(500, TimeUnit.MILLISECONDS).ignoring(NoSuchElementException.class);fluentWait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[@id='shibboleth']")));browser.findElement(By.xpath("//div[@id='shibboleth']/p[1]/a")).click();fluentWait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//form[@id='login']")));// Now we're at the login pageWebElement username = browser.findElement(By.xpath("//form[@id='login']/input[1]"));WebElement password = browser.findElement(By.xpath("//form[@id='login']/input[2]"));// Signs into the bobst reserve with the user's username and passwordusername.sendKeys(users.get(i).getUsername());password.sendKeys(users.get(i).getPassword()); browser.findElement(By.xpath("//form[@id='login']/input[3]")).click();if (browser.getCurrentUrl().equals("https://shibboleth.nyu.edu:443/idp/Authn/UserPassword") ||(browser.getCurrentUrl().equals("https://shibboleth.nyu.edu/idp/Authn/UserPassword")))throw new InvalidLoginException("User " + i + " had invalid login credentials");// START OF FUCKING AROUND WITH THE DATEPICKER// Error checking that rooms.library.nyu.edu pops upint count = 0;while ((!browser.getCurrentUrl().equals("https://rooms.library.nyu.edu/")) && (count < 5)){browser.navigate().refresh();Thread.sleep(5000);fluentWait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[@class='well well-sm']")));++count;}browser.findElement(By.xpath("//form[@class='form-horizontal']/div[@class='well well-sm']" + "/div[@class='form-group has-feedback']/div[@class='col-sm-6']/input[1]")).click();Thread.sleep(5000);// Checks the month and year, utilizes a wait for the year for the form to pop upWebElement datePickerYear = fluentWait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[@id='ui-datepicker-div']/div[@class='ui-datepicker-group ui-datepicker-group-first']/" + "div[@class='ui-datepicker-header ui-widget-header ui-helper-clearfix ui-corner-left']/" + "div[@class='ui-datepicker-title']/span[@class='ui-datepicker-year']")));String datePickerYearText = datePickerYear.getText();WebElement datePickerMonth = browser.findElement(By.xpath("//div[@id='ui-datepicker-div']/div[@class='ui-datepicker-group ui-datepicker-group-first']/" + "div[@class='ui-datepicker-header ui-widget-header ui-helper-clearfix ui-corner-left']/" +"div[@class='ui-datepicker-title']/span[@class='ui-datepicker-month']"));String datePickerMonthText = datePickerMonth.getText();// Alters yearwhile (!datePickerYearText.equals(reservationYear)){// Right clicks the month until it is the correct yearbrowser.findElement(By.className("ui-icon-circle-triangle-e")).click();// Updates the datepicker yeardatePickerYear = browser.findElement(By.xpath("//div[@id='ui-datepicker-div']/div[@class='ui-datepicker-group ui-datepicker-group-first']/" + "div[@class='ui-datepicker-header ui-widget-header ui-helper-clearfix ui-corner-left']/" + "div[@class='ui-datepicker-title']/span[@class='ui-datepicker-year']"));datePickerYearText = datePickerYear.getText();}// ALters monthwhile (!datePickerMonthText.equals(reservationMonth)){// Right clicks the month until it is the correct monthbrowser.findElement(By.className("ui-icon-circle-triangle-e")).click();// Updates the datepicker monthdatePickerMonth = browser.findElement(By.xpath("//div[@id='ui-datepicker-div']/div[@class='ui-datepicker-group ui-datepicker-group-first']/" + "div[@class='ui-datepicker-header ui-widget-header ui-helper-clearfix ui-corner-left']/" +"div[@class='ui-datepicker-title']/span[@class='ui-datepicker-month']"));datePickerMonthText = datePickerMonth.getText();}// At this point, we are on the correct year & month. Now we select the datebrowser.findElement(By.linkText(reservationDay)).click();// END OF THE FUCKING DATEPICKER// Selects the start timeint timeStart = getTime(i);Select reservationHour = new Select(browser.findElement(By.cssSelector("select#reservation_hour")));reservationHour.selectByValue(Integer.toString(timeStart));Select reservationMinute = new Select(browser.findElement(By.cssSelector("select#reservation_minute")));reservationMinute.selectByValue("0");// Selects AM/PMSelect reservationAMPM = new Select(browser.findElement(By.cssSelector("select#reservation_ampm")));if (AM_PM)reservationAMPM.selectByValue("am");elsereservationAMPM.selectByValue("pm");// Selects the time lengthSelect timeLength = new Select(browser.findElement(By.cssSelector("select#reservation_how_long")));timeLength.selectByValue("120");// Generates the room/time pickerbrowser.findElement(By.xpath("//button[@id='generate_grid']")).click();WebElement alert = null;// Checks if the user has already reserved a room for the daytry{alert = fluentWait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[@class='alert alert-danger']")));}catch (TimeoutException e){// Does nothing, since it's a good thing}if (alert != null)throw new ReservationException("The user number: " + i + " has already reserved a room for today");// Waits for the reservation to pop upfluentWait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[@class='modal-content']/div[@class='modal-body']/div[@class='modal-body-content']")));WebElement descriptionElement = fluentWait.until(ExpectedConditions.presenceOfElementLocated(By.id("reservation_title")));descriptionElement.sendKeys(description);// Fills in the duplicate email for the bookingWebElement duplicateEmailElement = browser.findElement(By.id("reservation_cc"));duplicateEmailElement.sendKeys(users.get(i).getEmailDuplicate());// Selects the row on the room pickerString roomText = "Bobst " + floorNumber + "-" + roomNumber;// Locates the roomWebElement divFind = browser.findElement(By.xpath("//form[@id='new_reservation']/table[@id='availability_grid_table']/tbody/tr[contains(., '" + roomText + "')]"));WebElement timeSlot = null;// Tries to get the next best time if it doesn't worktry{timeSlot = divFind.findElement(By.xpath("td[@class='timeslot timeslot_available timeslot_preferred']"));}catch (NoSuchElementException e){System.err.println("The timeslot was already taken for user: " + i + ", taking next best time");boolean found = false;// Continuously clicks the next button and checks until a time is foundwhile (found == false){try{// Clicks the button oncebrowser.findElement(By.xpath("//div[@class='rebuild_grid rebuild_grid_next']")).click();// Rechecks to find the timeSlottimeSlot = divFind.findElement(By.xpath("td[@class='timeslot timeslot_available timeslot_preferred']"));// If it gets to this point, the timeslot is found, sets found = truefound = true;}catch (NoSuchElementException ex){// Still didn't find an available timeslot, continues search} } // End of while loop} // End of finding a time if original preference could not be foundtimeSlot.click();// Submitsbrowser.findElement(By.xpath("//button[@class='btn btn-lg btn-primary']")).click();// Waits a bit for confirmation to occurFluentWait<WebDriver> buttonWait = new FluentWait<WebDriver>(browser).withTimeout(15, TimeUnit.SECONDS).pollingEvery(500, TimeUnit.MILLISECONDS).ignoring(NoSuchElementException.class);buttonWait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[@class='alert alert-success']")));// Final status updateSystem.out.println("User number " + i + " status: successful");// Updates the dailyStatus logString militaryTime = toMilitaryTime(i);System.out.println(militaryTime + ": Reserved");Thread.sleep(3000);}catch (UserNumberException e){System.err.println(e.getMessage());System.out.println("User number " + i + " status: failed");// Updates the dailyStatus logString militaryTime = toMilitaryTime(i);System.out.println(militaryTime + ": Not Reserved");}catch(ReservationException e){System.err.println(e.getMessage());System.out.println("User number " + i + " status: failed");// Updates the dailyStatus logString militaryTime = toMilitaryTime(i);System.out.println(militaryTime + ": Not Reserved");}catch(TimeoutException e){System.err.println(e.getMessage());System.out.println("User number " + i + " status: failed");// Updates the dailyStatus logString militaryTime = toMilitaryTime(i);System.out.println(militaryTime + ": Not Reserved");}catch(InvalidLoginException e){System.err.println(e.getMessage());System.out.println("User number " + i + " status: failed");// Updates the dailyStatus logString militaryTime = toMilitaryTime(i);System.out.println(militaryTime + ": Not Reserved");}catch (InterruptedException e){System.err.println("Sleep at end was interrupted");System.out.println("User number " + i + " status: failed");// Updates the dailyStatus logString militaryTime = toMilitaryTime(i);
            System.out.println(militaryTime + ": Not Reserved");}catch (Exception e){System.err.println("Shit, something happened that wasn't caught");System.out.println("User number " + i + " status: failed");e.printStackTrace();// Updates the dailyStatus logString militaryTime = toMilitaryTime(i);System.out.println(militaryTime + ": Not Reserved");}finally{// Logs outbrowser.get("https://rooms.library.nyu.edu/logout");try{Thread.sleep(10000);}catch (InterruptedException e1){System.err.println("Something wrong when trying to sleep after logout");}// Deletes cookiesbrowser.manage().deleteAllCookies();browser.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);// Closes the browser connectionbrowser.close();System.out.println("Browser is now closed");try {Thread.sleep(5000);}catch (InterruptedException e){System.err.println("Sleep at end was interrupted");}}} //End of for loop// Closes logging streamsif (pOut != null)pOut.close();if (pErr != null)pErr.close();if (fOut != null){try{fOut.close();}catch (IOException e){System.err.println("File output logging stream had errors when closing");}}if (fErr != null){try{fErr.close();}catch (IOException e){System.err.println("File output error stream had errors when closing");}}
}

  

转载于:https://www.cnblogs.com/lincj/p/7026179.html

selenium fluentwait java实例相关推荐

  1. java实例方法,Java实例和静态方法

    本篇文章帮大家学习java实例和静态方法,包含了java实例和静态方法使用方法.操作技巧.实例演示和注意事项,有一定的学习价值,大家可以用来参考. 类可以有两种类型的方法:实例方法和类方法. 实例方法 ...

  2. Java-Runoob-高级教程-实例-数组:01. Java 实例 – 数组排序及元素查找

    ylbtech-Java-Runoob-高级教程-实例-数组:01. Java 实例 – 数组排序及元素查找 1.返回顶部 1. Java 实例 - 数组排序及元素查找  Java 实例 以下实例演示 ...

  3. Java-Runoob-高级教程-实例-字符串:13. Java 实例 - 字符串格式化

    ylbtech-Java-Runoob-高级教程-实例-字符串:13. Java 实例 - 字符串格式化 1.返回顶部 1. Java 实例 - 字符串格式化  Java 实例 以下实例演示了通过 f ...

  4. jni java共享变量_Android JNI开发系列(十)JNI访问 Java 实例变量和静态变量

    JNI访问 Java 实例变量和静态变量 Java 中的实例变量和静态变量,在本地代码中如何来访问和修改.静态变量也称为类变量(属性),在所有实例对象中共享同一份数据,可以直接通过类名.变量名来访问. ...

  5. java 方法重载 应用举例,Java 实例 - 重载(overloading)方法中使用 Varargs

    以下实例演示了如何在重载方法中使用可变参数:/* author by w3cschool.cc Main.java */public class Main { static void vaTest(i ...

  6. Java实例开发教程:SpringBoot开发案例

    最近在做邮件发送的服务,正常来说SpringBoot整合mail还是很方便的,然而来了新的需求:A请求使用邮箱C发送,B请求使用邮箱D发送,也就是说我们需要配置两套发送服务. 单实例 首先我们来看下单 ...

  7. java实例变量可以被覆盖吗_Java继承覆盖实例变量

    参见英文答案 > Java Inheritance – instance variables overriding                                    3个 我 ...

  8. java使用varargs,Java 实例 – Varargs 可变参数使用 - Java 基础教程

    Java 实例 Java1.5提供了一个叫varargs的新功能,就是可变长度的参数. "Varargs"是"variable number of arguments&q ...

  9. Thrift入门及Java实例演示

    来源:http://www.micmiu.com/soa/rpc/thrift-sample/ Thrift入门及Java实例演示 作者: Michael日期: 2012 年 6 月 14 日 发表评 ...

最新文章

  1. ClickHouse系列教程八:从一个服务器导入4T数据到另外一个服务器
  2. IMXRT1052/1064 如何将代码存放在ITCM中
  3. CSDP是个好东西——CSDP 认证考试简介
  4. 你真的了解引用传递与值传递吗?
  5. BufferedOutputStream_字节缓冲输出流
  6. java 文件通配符_Java中泛型通配符的使用方法示例
  7. ANDROID PAD版本号 PHONE版本号 源代码有什么 差别?
  8. c重启mysql_不重启Mysql修改root密码的方法
  9. springboot项目java生成kml文件
  10. 第三期:ArcMap基础
  11. 传智播客黑马java 30期_黑马传智播客JavaEE57期 2019最新基础+就业+在职加薪_汇总...
  12. 从无到有 win10建window xp虚拟机之总结
  13. 面对疫情,大学生如何保持良好的心理状态
  14. STC 数码管显示及74HC573在其中的应用
  15. 了解一下nested数据类型
  16. 前端展示json格式数组
  17. 9.Python之异常处理
  18. 免费赠书啦!逃离帝都,书搬不动,大量AI类、技术类、科幻类书免费送给小伙伴...
  19. Axure-蒙版遮罩,鼠标移入移出点击效果设置,登录注册页面
  20. 扫地机器人航顺HK32F030K6T6方案

热门文章

  1. CVPR 2021 | 超越卷积,自注意力模型HaloNet
  2. 收藏 | 使用 YOLO及OpenCV 实现目标检测
  3. MIT最新课程:一文看尽深度学习各领域最新突破(附视频、PPT)
  4. 数据结构期末复习之交换排序
  5. 使用 加载 顺序_SpringBoot系列教程之Bean加载顺序之错误使用姿势辟谣
  6. python实现决策树归纳_决策树【python实现】
  7. ssh 登陆错误后禁止ip再次登陆_macOS破坏SSH默认规则,程序员无法登录Web服务器...
  8. 手把手教你IDEA使用GIT进行项目管理
  9. USB 3.0、USB 3.1到底什么区别?
  10. 2019年最值得关注的5个人工智能趋势!