/** * Fills an autocomplete field with a given value. * * @param driver The WebDriver instance we are working with * @param value The new value, or null to generate a non-empty value * @param autocompleteInputElement The WebElement into which we are inputting the value */ public static void fillAutocompleteField( WebDriver driver, WebElement autocompleteInputElement, String value) { if (autocompleteInputElement != null) { autocompleteInputElement.click(); autocompleteInputElement.sendKeys(value); new WebDriverWait(driver, 10) .until( ExpectedConditions.visibilityOfElementLocated(By.className("cs-autocomplete-popup"))); WebElement popupElement = driver.findElement(By.className("cs-autocomplete-popup")); WebElement matchesElement = popupElement.findElement(By.className("csc-autocomplete-Matches")); WebElement matchSpanElement = null; new WebDriverWait(driver, 10) .until( ExpectedConditions.visibilityOfElementLocated(By.className("cs-autocomplete-popup"))); for (WebElement candidateMatchElement : matchesElement.findElements(By.tagName("li"))) { WebElement candidateMatchSpanElement = candidateMatchElement.findElement(By.tagName("span")); if (candidateMatchSpanElement.getText().equals(value)) { matchSpanElement = candidateMatchSpanElement; break; } } if (matchSpanElement != null) { // Click the value if found new WebDriverWait(driver, 10) .until( ExpectedConditions.visibilityOfElementLocated( By.className("cs-autocomplete-popup"))); matchSpanElement.click(); } else { // create a new authority item if one matching it does not already exist new WebDriverWait(driver, 10) .until( ExpectedConditions.visibilityOfElementLocated( By.className("cs-autocomplete-popup"))); WebElement addToPanelElement = popupElement.findElement(By.className("csc-autocomplete-addToPanel")); WebElement firstAuthorityItem = addToPanelElement.findElement(By.tagName("li")); firstAuthorityItem.click(); while (findElementsWithTimeout(driver, 0, By.className("cs-autocomplete-popup")).size() > 0) { // Wait for the popup to close } } } else { } }
public void verifyCommentRowContent( String commentRowIdSuffix, String commentText, String giverName) { WebDriverWait wait = new WebDriverWait(browser.driver, 30); WebElement commentRow; try { commentRow = wait.until( ExpectedConditions.presenceOfElementLocated( By.id("responseCommentRow" + commentRowIdSuffix))); } catch (TimeoutException e) { fail("Timeout!"); commentRow = null; } try { wait.until( ExpectedConditions.textToBePresentInElement( commentRow.findElement(By.id("plainCommentText" + commentRowIdSuffix)), commentText)); } catch (TimeoutException e) { fail("Not expected message"); } try { assertTrue(commentRow.findElement(By.className("text-muted")).getText().contains(giverName)); } catch (AssertionError e) { assertTrue(commentRow.findElement(By.className("text-muted")).getText().contains("you")); } }
/** * Click the removal link for a language. * * @param localeId language to remove * @return new language settings tab */ public ProjectLanguagesTab removeLocale(final String localeId) { log.info("Click Remove on {}", localeId); boolean removedLocale = false; for (WebElement localeLi : getEnabledLocaleListElement()) { String displayedLocaleId = localeLi.findElement(By.xpath(".//span")).getText().replace("[", "").replace("]", ""); if (displayedLocaleId.equals(localeId)) { localeLi.findElement(By.tagName("a")).click(); removedLocale = true; break; } } Preconditions.checkState(removedLocale, "can not remove locale: %s", localeId); refreshPageUntil( this, new Predicate<WebDriver>() { @Override public boolean apply(WebDriver driver) { return !getEnabledLocaleList().contains(localeId); } }); return new ProjectLanguagesTab(getDriver()); }
// odi.614 Able to generate reports for time range public void search() { String dmName = "US_AIRWAYS"; gotoreports(dmName); try { driver.findElement(By.id("PARAM_START_DATE")).clear(); Alert alert = driver.switchTo().alert(); alert.dismiss(); driver.findElement(By.id("PARAM_START_DATE")).sendKeys("8/11/2013"); driver.findElement(By.id("PARAM_END_DATE")).clear(); alert.dismiss(); driver.findElement(By.id("PARAM_END_DATE")).sendKeys("9/11/2013"); driver.findElement(By.cssSelector("input[type=\"submit\"]")).click(); driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); new WebDriverWait(driver, 10) .until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("reportContent")); WebElement page = new WebDriverWait(driver, 10) .until(ExpectedConditions.visibilityOfElementLocated(By.id("CrystalViewer"))); WebElement rangeStart = page.findElement(By.xpath("//*[contains(text(),'8/11/2013')]")); WebElement rangeEnd = page.findElement(By.xpath("//*[contains(text(),'9/11/2013')]")); if (rangeStart != null && rangeEnd != null) { System.out.println("Report for selected range is showed"); } ReportFile = new WriteXmlFile(); driver.switchTo().defaultContent(); ReportFile.addTestCase("ODI6.x-614:CSSR-Search", "ODI6.x-614:CSSR-Search => Pass"); } catch (Exception e) { System.out.print("trace: "); e.printStackTrace(); } // driver.quit(); ReportFile.WriteToFile(); }
public static void extractnews(String symbol, String path) throws InterruptedException, IOException { // WebDriver driver = new HtmlUnitDriver(); WebDriver driver = new FirefoxDriver(); driver.get("http://www.otcmarkets.com/stock/" + symbol + "/insider-transactions"); Thread.sleep(3000); boolean next = true; int count = -1; while (next) { next = false; count++; // grab the whole page and the link File file = new File(path + driver.getCurrentUrl().replaceAll("/", "_") + '_' + count); if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file); fw.write(driver.getPageSource()); fw.flush(); fw.close(); System.out.println(driver.getCurrentUrl() + '/' + count); // System.out.println(driver.getPageSource()); // check for the next button, if found then click set the flag to true WebElement pagination = null; try { pagination = driver.findElement(By.id("shortInterestTable")).findElement(By.className("pageList")); } catch (Exception e) { continue; } List<WebElement> paginationli = pagination.findElements(By.tagName("li")); for (WebElement ele : paginationli) { try { ele.findElement(By.tagName("a")).getText(); } catch (Exception e) { continue; } if (ele.findElement(By.tagName("a")).getText().equals("next >")) { // System.out.println("HI"); WebElement nextpage = ele.findElement(By.tagName("a")); nextpage.click(); next = true; Thread.sleep(3000); } } } driver.quit(); }
public WebElementFacade findBy(String xpathOrCssSelector) { WebElement nestedElement = null; if (PageObject.isXPath(xpathOrCssSelector)) { nestedElement = webElement.findElement((By.xpath(xpathOrCssSelector))); } else { nestedElement = webElement.findElement((By.cssSelector(xpathOrCssSelector))); } return new WebElementFacade(driver, nestedElement, timeoutInMilliseconds); }
private void rebuildCache() { cachedContacts = new SortedListOf<ContactData>(); manager.navigateTo().mainPage(); List<WebElement> contactRows = driver.findElements(By.xpath("//tr[@name='entry']")); for (WebElement contactRow : contactRows) { String fname = contactRow.findElement(By.xpath("./td[3]")).getText(); String lname = contactRow.findElement(By.xpath("./td[2]")).getText(); String mail1 = contactRow.findElement(By.xpath("./td[4]")).getText(); String hnumber = contactRow.findElement(By.xpath("./td[5]")).getText(); cachedContacts.add((ContactData) new ContactData().withFname(fname)); } }
/* * Return the configurations of only one config * Example : all the disks and os configs of the "Extra-Large" config */ public void addConfigurationsExoScale(String configName, boolean windows) throws Exception { List<WebElement> articles = driver.findElements(By.className("vm-card")); for (WebElement article : articles) { WebElement h3 = article.findElement(By.tagName("h3")); if (h3.getText().equals(configName)) { WebElement parent = h3.findElement(By.xpath("..")); parent.click(); } } if (windows) { WebElement windowsButton = driver.findElement(By.className("win")); windowsButton.click(); } WebElement minusButton = driver.findElement(By.className("stepper-subtract")); while (!(minusButton.getAttribute("class").contains("disabled"))) { minusButton.click(); } // System.out.println("minusButton-class : "+minusButton.getAttribute("class")); WebElement cpu = driver .findElement(By.className("summary")) .findElement(By.className("cpu")) .findElement(By.className("spec-value")); int cpuValue = Integer.parseInt(cpu.getText()); // System.out.println("cpu : "+cpuValue); WebElement ram = driver .findElement(By.className("summary")) .findElement(By.className("ram")) .findElement(By.className("spec-value")); double ramValue = this.extractNumber(ram.getText()); if (ram.getText().contains("MB")) { ramValue /= 1000; // Given in MB } // System.out.println("ram : "+ramValue); WebElement plusButton = driver.findElement(By.className("stepper-add")); // System.out.println("plusButton-class : "+plusButton.getAttribute("class")); // Inside the while will be one configuration. It has to be added to the configs arrayList while (!(plusButton.getAttribute("class").contains("disabled"))) { this.addConfigurationExoScale(configName, cpuValue, ramValue, windows); plusButton.click(); } // For the last one that can't be inside the while because of the disabled plusButton this.addConfigurationExoScale(configName, cpuValue, ramValue, windows); }
public void clickOnShowComments() { for (WebElement element : getListOfTweets()) { WebElement commentsNumberElement = element.findElement(By.id("commentsNumber")); Integer commentsNumber = Integer.parseInt(commentsNumberElement.getText()); if (commentsNumber > 0) { WebElement showCommentsLink = element.findElement(By.id("showCommentsLink")); showCommentsLink.click(); break; } } }
public void editFeedbackResponseComment(String commentIdSuffix, String newCommentText) { WebElement commentRow = browser.driver.findElement(By.id("responseCommentRow" + commentIdSuffix)); commentRow.findElements(By.tagName("a")).get(1).click(); WebElement commentEditForm = browser.driver.findElement(By.id("responseCommentEditForm" + commentIdSuffix)); fillTextBox(commentEditForm.findElement(By.name("responsecommenttext")), newCommentText); commentEditForm .findElement(By.className("col-sm-offset-5")) .findElement(By.tagName("a")) .click(); ThreadHelper.waitFor(1000); }
public String getTextForFollowButton(String userName) { String buttonText = ""; if (StringUtils.isEmpty(userName)) { throw new IllegalArgumentException("Name can't be empty or null"); } List<WebElement> elements = findAndWaitForElements(By.cssSelector("tbody.yui-dt-data > tr")); for (WebElement webElement : elements) { if ((webElement.findElement(By.tagName("a")).getText()).contains(userName)) { buttonText = webElement.findElement(By.tagName("button")).getText(); break; } } return buttonText; }
public void clickVisibilityOptionForResponseCommentAndSave( String idString, int numOfTheCheckbox) { String idSuffix = idString.substring(18); WebElement commentRow = browser.driver.findElement(By.id(idString)); commentRow.findElements(By.tagName("a")).get(1).click(); WebElement commentEditForm = browser.driver.findElement(By.id("responseCommentEditForm" + idSuffix)); commentRow.findElement(By.id("frComment-visibility-options-trigger" + idSuffix)).click(); commentRow.findElements(By.cssSelector("input[type='checkbox']")).get(numOfTheCheckbox).click(); commentEditForm .findElement(By.className("col-sm-offset-5")) .findElement(By.tagName("a")) .click(); ThreadHelper.waitFor(1000); }
public List<WebElement> getExistingTemplatesLinks() { WebElement availableTemplatesHeader = getDriver().findElement(By.id("HAvailableTemplateProviders")); // a bit unreliable here, but it's the best I can do WebElement ul = availableTemplatesHeader.findElement(By.xpath("following-sibling::node()")); return ul.findElements(By.tagName("a")); }
/** @since 5.9.3 */ public void removeFromSelection(final String displayedText) { if (!multiple) { throw new UnsupportedOperationException( "The select2 is not multiple, use #removeSelection instead"); } final String submittedValueBefore = getSubmittedValue(); boolean found = false; for (WebElement el : getSelectedValues()) { if (el.getText().equals(displayedText)) { Locator.waitUntilEnabledAndClick( el.findElement(By.xpath("a[@class='select2-search-choice-close']"))); found = true; } } if (found) { Locator.waitUntilGivenFunction( new Function<WebDriver, Boolean>() { @Override public Boolean apply(WebDriver driver) { return !submittedValueBefore.equals(getSubmittedValue()); } }); } else { throw new ElementNotFoundException( "remove link for select2 '" + displayedText + "' item", "", ""); } }
private void next() { WebElement element = cataloguePage.getMainBlock().getNextPage(); if (!CollectionUtils.isEmpty(element.findElements(By.className(NavigationLine.ACTIVE_LINK)))) { element.findElement(By.className(NavigationLine.ACTIVE_LINK)).click(); } }
protected void setCheckboxState(WebElement checkboxElement, boolean checked) { if ((checked == true && !isCheckboxChecked(checkboxElement)) || (checked == false && isCheckboxChecked(checkboxElement))) { WebElement trigger = checkboxElement.findElement(By.cssSelector("div.ui-chkbox-box")); Graphene.guardAjax(trigger).click(); } }
protected boolean isWidgetVisible(int widgetIndex) { WebElement polldaddyWidget = polldaddyDivList.get(widgetIndex); wait.forElementVisible(polldaddyWidget); wait.forElementVisible(polldaddyWidget.findElement(polldaddyBody)); return true; }
public void deleteRedemptionCode(String code) { WebElement thisCodeRow = getCodeTableRow(code); Assert.assertNotNull(thisCodeRow, "Row with code " + code + "not found."); thisCodeRow.findElement(By.xpath("./td[3]/a")).click(); deleteConfirm.click(); }
protected void selectOptionByLabel(WebElement menuElement, String text, boolean guardAjax) { String menuId = getEscapedElementId(menuElement); WebElement trigger = menuElement.findElement(By.cssSelector("div.ui-selectonemenu-trigger")); trigger.click(); String menuItemsContainerId = menuId + "_panel"; List<WebElement> options = driver.findElements( By.cssSelector("#" + menuItemsContainerId + " tr.ui-selectonemenu-item")); if (options.isEmpty()) { options = driver.findElements( By.cssSelector("#" + menuItemsContainerId + " li.ui-selectonemenu-item")); } String selectedOptionText = getSelectedOptionText(menuElement); for (WebElement option : options) { if (option.getAttribute("data-label").equals(text)) { if (guardAjax && !selectedOptionText.equals(text)) { Graphene.guardAjax(option).click(); } else { option.click(); } break; } } }
public SpeakeasyUserPage unfavorite(String pluginKey) { WebElement pluginRow = getPluginRow(pluginKey); WebElement link = pluginRow.findElement(By.className("favorite-icon")); link.click(); waitForMessages(); return this; }
@JavascriptEnabled @Test public void testDragAndDrop() throws InterruptedException { driver.get(pages.droppableItems); long waitEndTime = System.currentTimeMillis() + 15000; while (!isElementAvailable(driver, By.id("draggable")) && (System.currentTimeMillis() < waitEndTime)) { Thread.sleep(200); } if (!isElementAvailable(driver, By.id("draggable"))) { throw new RuntimeException("Could not find draggable element after 15 seconds."); } WebElement toDrag = driver.findElement(By.id("draggable")); WebElement dropInto = driver.findElement(By.id("droppable")); Action holdDrag = getBuilder(driver).clickAndHold(toDrag).build(); Action move = getBuilder(driver).moveToElement(dropInto).build(); Action drop = getBuilder(driver).release(dropInto).build(); holdDrag.perform(); move.perform(); drop.perform(); dropInto = driver.findElement(By.id("droppable")); String text = dropInto.findElement(By.tagName("p")).getText(); assertEquals("Dropped!", text); }
public WebElement getCell(final WebElement calendar) { return calendar .findElement(By.tagName("tbody")) .findElements(By.tagName("tr")) .get(1) .findElement(By.tagName("td")); }
private WebElement getCodeTableRow(String code) { boolean hasNextLink; do { List<WebElement> rows = app.getDriver() .findElements( By.xpath( "//form[@id='esl-redemption-code-overview-form']/div/table[2]/tbody/tr")); for (WebElement row : rows) { String codeCell = row.findElement(By.xpath("./td[1]")).getText(); if (codeCell.equals(code)) { return row; } } hasNextLink = isElementPresent(By.xpath("//ul[@class='pager']/li[@class='pager-next']/a")); if (hasNextLink) { app.getDriver() .findElement(By.xpath("//ul[@class='pager']/li[@class='pager-next']/a")) .click(); } } while (hasNextLink); return null; }
protected boolean addTable(WebElement procedureDescToolBar, String data) throws InterruptedException { boolean created; WebElement tableLoader = procedureDescToolBar.findElement(By.cssSelector(".grid.load")); tableLoader.click(); TimeUnit.SECONDS.sleep(4); writeInTable(data); TimeUnit.SECONDS.sleep(2); WebElement imgSaveDesc = driverWait.until( ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".fa.fa-check"))); imgSaveDesc.click(); TimeUnit.SECONDS.sleep(4); driverWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".delete_me"))); String value = readFromTable(); WebElement tableArea = driverWait.until( ExpectedConditions.visibilityOfElementLocated( By.cssSelector(".inline_form_container.type_excel.spreadJS_activated"))); created = ((tableArea != null) && (data.equals(value))); return created; }
public WebElement findElement(By by) { for (WebElement webElement : this) { WebElement element = webElement.findElement(by); if (element != null) return element; } return null; }
// Returns the number of replies to a post protected int getPostRepliesCount(String strPostDataPath) { int nReplies = 0; WebElement elemPost = getPostByDataPathOrFail(strPostDataPath); String strReplies = null; setDefaultWaitTime(2); try { /* <div class="detail-entry-replies"> <i class="icon-replies" title="Replies"></i> <span class="replies-count" title="Replies">0</span> */ String strRepliesXPath = ".//span[@class='replies-count' and @title='Replies']"; WebElement elemRepliesCount = elemPost.findElement(By.xpath(strRepliesXPath)); strReplies = elemRepliesCount.getText(); } catch (NoSuchElementException ex) { fail( "Could not find the number of replies on the post with the data path " + strPostDataPath); } resetDefaultWaitTime(); try { nReplies = Integer.parseInt(strReplies); } catch (NumberFormatException ex) { fail("Could not parse an integer out of \"" + strReplies + "\": " + ex.getMessage()); } return nReplies; } // getPostRepliesCount
public boolean deleteWebApp(String webAppContext) throws Exception { WebElement table_element = driver.findElement(By.id("webappsTable")); List<WebElement> tr_collection = table_element.findElement(By.tagName("tbody")).findElements(By.tagName("tr")); if (tr_collection.size() == 0) { throw new Exception("Web App you are trying to delete not exists"); } List<WebElement> td_collection; for (WebElement tr : tr_collection) { td_collection = tr.findElements(By.tagName("td")); if (webAppContext.equals(td_collection.get(1).getText())) { td_collection.get(0).findElement(By.tagName("input")).click(); driver.findElement(By.id("delete2")).click(); Assert.assertEquals( driver.findElement(By.id("messagebox-confirm")).getText(), "Do you want to delete the selected applications?", "Delete Confirmation message mismatched"); List<WebElement> buttons = driver.findElements(By.tagName("button")); for (WebElement button : buttons) { if ("yes".equalsIgnoreCase(button.getText())) { button.click(); break; } } Assert.assertEquals( driver.findElement(By.id("messagebox-info")).getText(), "Successfully deleted selected applications", "Web Application deletion failed" + ". Message box content mis matched"); driver.findElement(By.xpath("/html/body/div[3]/div[2]/button")).click(); return true; } } throw new Exception("Web App you are trying to delete not exists"); }
public boolean findWebApp(String webAppContext) { WebElement table_element = driver.findElement(By.id("webappsTable")); List<WebElement> tr_collection = table_element.findElement(By.tagName("tbody")).findElements(By.tagName("tr")); log.info("Number of rows in webapp table = " + tr_collection.size()); if (tr_collection.size() == 0) { return false; } int row_num, col_num; row_num = 1; for (WebElement trElement : tr_collection) { List<WebElement> td_collection = trElement.findElements(By.tagName("td")); col_num = 1; for (WebElement tdElement : td_collection) { log.info("row # " + row_num + ", col # " + col_num + "text=" + tdElement.getText()); if (tdElement.getText().equals(webAppContext)) { log.info("Webapp context found"); return true; } col_num++; } row_num++; } return false; }
public MetricsAreaFragment getMetricsArea(String title) { ////// add property By selector = By.xpath( ".//table[contains(@class, '" + PropUtils.get("metrics.container.class") + "')][.//h3[text()='" + title + "']]"); WebElement element = null; try { element = getContentRoot().findElement(selector); } catch (NoSuchElementException exc) { return null; } MetricsAreaFragment area = Graphene.createPageFragment(MetricsAreaFragment.class, element); Map<String, String> metricGrid = element .findElement(By.className(PropUtils.get("metrics.grid.class"))) .findElements(By.tagName("tr")) .stream() .collect( Collectors.toMap( e -> e.findElement(By.className(PropUtils.get("metrics.grid.nominal.class"))) .getText(), e -> e.findElement(By.className(PropUtils.get("metrics.grid.numerical.class"))) .getText())); area.setMetricGrid(metricGrid); return area; }
protected String addTextToDesc(String toolBarXPath, String descToTest) throws InterruptedException { WebElement descriptionToolBar = getWebDriver().findElement(By.xpath(toolBarXPath)); TimeUnit.SECONDS.sleep(2); WebElement textLoader = descriptionToolBar.findElement(By.cssSelector(".text.load")); textLoader.click(); writeInRedactor(descToTest); WebElement saveDescription = driverWait.until( ExpectedConditions.visibilityOfElementLocated(By.xpath(".//*[@title='Save']"))); saveDescription.click(); WebElement text = driverWait.until( ExpectedConditions.visibilityOfElementLocated( By.xpath(".//*[starts-with(@id,'form_for_textarea_')]/span"))); String description = text.getText(); return description; }