How to use findElements method of org.openqa.selenium.support.ByIdOrName class

Best Selenium code snippet using org.openqa.selenium.support.ByIdOrName.findElements

copy

Full Screen

...37 public void findInstructionsByIdOrName(){38 /​/​ findElement returns the element with the id if it exists, and if not searches for it via the name39 final WebElement instructionsPara = driver.findElement(40 new ByIdOrName("instruction-text"));41 final List<WebElement> instructionsParaAgain = driver.findElements(42 new ByIdOrName("instructions"));43 Assertions.assertEquals(instructionsPara.getText(),44 instructionsParaAgain.get(0).getText());45 }46 @Test47 public void quotesEscapingToCreateXPath(){48 Assertions.assertEquals("\"literal\"",49 Quotes.escape("literal"));50 Assertions.assertEquals("\"'single-quoted'\"",51 Quotes.escape("'single-quoted'"));52 Assertions.assertEquals("'\"double-quoted\"'",53 Quotes.escape("\"double-quoted\""));54 Assertions.assertEquals("concat(\"\", '\"', \"quot'end\", '\"')",55 Quotes.escape("\"quot'end\""));56 Assertions.assertEquals("concat(\"'quo\", '\"', \"ted'\")",57 Quotes.escape("'quo\"ted'"));58 }59 @Test60 public void checkColors(){61 final WebElement title = driver.findElement(By.id("instruction-title"));62 /​/​ Colors is an enum of named Color objects63 final Color blackValue = Colors.BLACK.getColorValue();64 /​/​ Color has methods to help convert between RBG, HEX65 Assertions.assertEquals("#000000",blackValue.asHex());66 Assertions.assertEquals("rgba(0, 0, 0, 1)",blackValue.asRgba());67 Assertions.assertEquals("rgb(0, 0, 0)",blackValue.asRgb());68 /​/​ color values returned by WebElement's getCSSValue are always69 /​/​ RGBA format, not the HTML source HEX or RGB70 Assertions.assertEquals(title.getCssValue("background-color"),71 blackValue.asRgba());72 /​/​ can create custom colors using the RGB input constructor73 /​/​ if the Colors enum does not have what we need74 final Color redValue = new Color(255,0,0, 1);75 Assertions.assertEquals(title.getCssValue("color"), redValue.asRgba());76 }77 @Test78 public void waitForMessage() {79 final WebElement selectMenu = driver.findElement(By.id("select-menu"));80 final Select select = new Select(selectMenu);81 select.selectByVisibleText("Option 2");82 /​/​ We are so used to using WebDriverWait and the ExpectedConditions class83 /​/​ that we might not have realised these are part of the support packages84 new WebDriverWait(driver, 10).until(85 ExpectedConditions.textToBe(By.id("message"), "Received message: selected 2"));86 }87 @Test88 public void canGetInfoAboutSelect(){89 final WebElement selectMenu = driver.findElement(By.id("select-menu"));90 final Select select = new Select(selectMenu);91 /​/​ the isMultiple method should be false for the select-menu item92 final WebElement multiSelectMenu = driver.findElement(By.id("select-multi"));93 final Select multiSelect = new Select(multiSelectMenu);94 /​/​ the isMultiple method should be true for multi select95 Assertions.assertFalse(select.isMultiple());96 Assertions.assertTrue(multiSelect.isMultiple());97 }98 @Test99 public void canGetAllOptionsFromSelect(){100 final WebElement selectMenu = driver.findElement(By.id("select-menu"));101 final Select select = new Select(selectMenu);102 /​/​ getOptions will return a List of WebElement103 /​/​ and allow me to access the options using104 /​/​ simple List methods105 List<WebElement> options = select.getOptions();106 Assertions.assertEquals(4,options.size());107 Assertions.assertEquals("Option 1", options.get(0).getText());108 }109 @Test110 public void canSelectSingleOptions(){111 /​/​ demo test to show single-select capabilities112 final WebElement selectMenu = driver.findElement(By.id("select-menu"));113 final Select select = new Select(selectMenu);114 /​/​ select will do nothing because this option is selected by default115 select.selectByIndex(0);116 Assertions.assertEquals("Option 1", select.getFirstSelectedOption().getText());117 /​/​ I can select the second item by Index 1 to chooose Option 2118 select.selectByIndex(1);119 Assertions.assertEquals("Option 2", select.getFirstSelectedOption().getText());120 /​/​ I can select the first by using the value "1"121 select.selectByValue("1");122 Assertions.assertEquals("Option 1", select.getFirstSelectedOption().getText());123 /​/​ and I can select using the text in the option124 select.selectByVisibleText("Option 3");125 Assertions.assertEquals("3", select.getFirstSelectedOption().getAttribute("value"));126 }127 @Test128 public void canSelectAndDeselectMultiOptions(){129 /​/​ demo test to show multi-select capabilities130 final WebElement selectMenu = driver.findElement(By.id("select-multi"));131 final Select select = new Select(selectMenu);132 /​/​ make sure nothing is selected with deselectAll133 select.deselectAll();134 /​/​ A normal select by index to get the First item135 select.selectByIndex(0);136 Assertions.assertEquals("First", select.getFirstSelectedOption().getText());137 /​/​ if I select I can deselect - by index, text or value138 select.deselectByIndex(0);139 /​/​ when nothing is selected a NoSuchElementException is thrown140 Assertions.assertThrows(NoSuchElementException.class, () -> {141 select.getFirstSelectedOption(); });142 /​/​ select two items - values 20 and 30143 select.selectByValue("20");144 select.selectByValue("30");145 /​/​ use getAllSelectedOptions, there should be 2 in the list146 final List<WebElement> selected = select.getAllSelectedOptions();147 Assertions.assertEquals(2, selected.size());148 /​/​ assert on the getText for the list entries149 Assertions.assertEquals("Second", selected.get(0).getText());150 Assertions.assertEquals("Third", selected.get(1).getText());151 /​/​ deselect the first one - assert visible text "Second"152 select.deselectByVisibleText("Second");153 /​/​ and assert that the first selected option text is "Third"154 Assertions.assertEquals("Third", select.getFirstSelectedOption().getText());155 /​/​ deselect them all to finish156 select.deselectAll();157 Assertions.assertEquals(0, select.getAllSelectedOptions().size());158 Assertions.assertEquals(selectMenu, select.getWrappedElement());159 }160 /​/​@Disabled("To be enabled if run independently")161 @Test162 public void canClickAButton(){163 final WebElement buttonElement = driver.findElement(By.id("resend-select"));164 Button button = new Button(buttonElement);165 /​/​ rather than click on a button element,166 /​/​ could we click on a Button?167 Assertions.assertEquals("Resend Single Option Message",168 button.getText());169 button.click();170 new WebDriverWait(driver, 10).171 until(ExpectedConditions.textToBe(By.id("message"),172 "Received message: selected 1"));173 }174 @Test175 public void byIdOrName(){176 WebElement idButton = driver.findElement(By.id("resend-select"));177 Assertions.assertEquals("Resend Single Option Message",178 idButton.getText());179 WebElement namedButton = driver.findElement(By.name("resend-select"));180 Assertions.assertEquals("Resend Multi Option Message",181 namedButton.getText());182 /​/​ ByIdOrName can match by id, and if that doesn't match treat it as a name183 /​/​ use ByIdOrName to find a button element "resend-select"184 /​/​ and the assertions should pass185 WebElement button = driver.findElement(new ByIdOrName("resend-select"));186 Assertions.assertEquals(idButton, button);187 Assertions.assertNotEquals(namedButton, button);188 /​/​ByIdOrName findElements returns all id and name matches189 /​/​findElements for "resend-select" should find 2 buttons190 List<WebElement> buttons = driver.findElements(new ByIdOrName("resend-select"));191 Assertions.assertEquals(2, buttons.size());192 /​/​ the elements identified should be the same as we found initially193 Assertions.assertTrue(buttons.contains(idButton));194 Assertions.assertTrue(buttons.contains(namedButton));195 }196 @Test197 public void byAll(){198 /​/​ we could use ByAll to find by id or by name199 /​/​ by all is a collator, so given a number of locators, find all items that match200 final List<WebElement> buttons = driver.findElements(201 new ByAll(By.id("resend-select"),202 By.name("resend-select")));203 Assertions.assertEquals(2, buttons.size());204 Assertions.assertTrue(buttons.contains(driver.findElement(By.id("resend-select"))));205 Assertions.assertTrue(buttons.contains(driver.findElement(By.name("resend-select"))));206 }207 @Test208 public void byChained(){209 final WebElement resendSingle = driver.findElement(By.id("resend-select"));210 resendSingle.click();211 resendSingle.click();212 resendSingle.click();213 resendSingle.click();214 final WebElement resend = driver.findElement(By.id("resend-multi"));215 resend.click();216 resend.click();217 /​/​ TODO: make this more specific to only find messages under a 'list'218 final List<WebElement> allMessages = driver.findElements(219 new ByChained(By.name("list"),220 By.className("message")));221 Assertions.assertEquals(6, allMessages.size());222 /​/​ then just the #single list .message223 final List<WebElement> singleMessages = driver.findElements(224 new ByChained(By.id("single"),By.name("list"),225 By.className("message")));226 Assertions.assertEquals(4, singleMessages.size());227 /​/​ then the #multi list .message228 final List<WebElement> multiMessages = driver.findElements(229 new ByChained(By.id("multi"),By.name("list"),230 By.className("message")));231 Assertions.assertEquals(2, multiMessages.size());232 }233 @Test234 public void loggingFindingElements() {235 final By resend = By.id("resend-select");236 final By noSuchElement = By.id("no-such-element");237 EventFiringWebDriver events = new EventFiringWebDriver(driver);238 events.register(new LocalEventFiringListener());239 WebElement resendElem = events.findElement(resend);240 Assertions.assertNotNull(resendElem);241 Assertions.assertThrows(NoSuchElementException.class, () -> {242 events.findElement(noSuchElement);...

Full Screen

Full Screen
copy

Full Screen

...65 final WebElement element1 = mock(WebElement.class, "webElement1");66 final WebElement element2 = mock(WebElement.class, "webElement2");67 final List<WebElement> list = Arrays.asList(element1, element2);68 final WebElement rootElement = mock(WebElement.class);69 when(rootElement.findElements(by))70 .thenReturn(list);71 final WebDriver driver = mock(WebDriver.class);72 when(driver.findElement(rootElementBy))73 .thenReturn(rootElement);74 final ElementLocator locator = newLocator(driver, f);75 final List<WebElement> returnedList = locator.findElements();76 assertEquals(list, returnedList);77 }78 @Test79 void cachedElementShouldBeCached() throws Exception {80 final Field f = Block.class.getDeclaredField("cached");81 final By by = new ByIdOrName("cached");82 final WebElement element = mock(WebElement.class);83 final WebElement rootElement = mock(WebElement.class);84 when(rootElement.findElement(by))85 .thenReturn(element);86 final WebDriver driver = mock(WebDriver.class);87 when(driver.findElement(rootElementBy))88 .thenReturn(rootElement);89 final ElementLocator locator = newLocator(driver, f);90 locator.findElement();91 locator.findElement();92 verify(driver, times(1)).findElement(rootElementBy);93 verify(rootElement, times(1)).findElement(by);94 }95 @Test96 void cachedElementListShouldBeCached() throws Exception {97 final Field f = Block.class.getDeclaredField("cachedList");98 final By by = new ByIdOrName("cachedList");99 final WebElement element1 = mock(WebElement.class, "webElement1");100 final WebElement element2 = mock(WebElement.class, "webElement2");101 final List<WebElement> list = Arrays.asList(element1, element2);102 final WebElement rootElement = mock(WebElement.class);103 when(rootElement.findElements(by))104 .thenReturn(list);105 final WebDriver driver = mock(WebDriver.class);106 when(driver.findElement(rootElementBy))107 .thenReturn(rootElement);108 final ElementLocator locator = newLocator(driver, f);109 locator.findElements();110 locator.findElements();111 verify(driver, times(1)).findElement(rootElementBy);112 verify(rootElement, times(1)).findElements(by);113 }114 @Test115 void shouldNotCacheNormalElement() throws Exception {116 final Field f = Block.class.getDeclaredField("first");117 final By by = new ByIdOrName("first");118 final WebElement element = mock(WebElement.class);119 final WebElement rootElement = mock(WebElement.class);120 when(rootElement.findElement(by))121 .thenReturn(element);122 final WebDriver driver = mock(WebDriver.class);123 when(driver.findElement(rootElementBy))124 .thenReturn(rootElement);125 final ElementLocator locator = newLocator(driver, f);126 locator.findElement();127 locator.findElement();128 verify(driver, times(2)).findElement(rootElementBy);129 verify(rootElement, times(2)).findElement(by);130 }131 @Test132 void shouldNotCacheNormalElementList() throws Exception {133 final Field f = Block.class.getDeclaredField("list");134 final By by = new ByIdOrName("list");135 final WebElement element1 = mock(WebElement.class, "webElement1");136 final WebElement element2 = mock(WebElement.class, "webElement2");137 final List<WebElement> list = Arrays.asList(element1, element2);138 final WebElement rootElement = mock(WebElement.class);139 when(rootElement.findElements(by))140 .thenReturn(list);141 final WebDriver driver = mock(WebDriver.class);142 when(driver.findElement(rootElementBy))143 .thenReturn(rootElement);144 final ElementLocator locator = newLocator(driver, f);145 locator.findElements();146 locator.findElements();147 verify(driver, times(2)).findElement(rootElementBy);148 verify(rootElement, times(2)).findElements(by);149 }150 @Test151 void shouldUseFindByAnnotationsWherePossible() throws Exception {152 final Field f = Block.class.getDeclaredField("byId");153 final By by = By.id("foo");154 final WebElement element = mock(WebElement.class);155 final WebElement rootElement = mock(WebElement.class);156 when(rootElement.findElement(by))157 .thenReturn(element);158 final WebDriver driver = mock(WebDriver.class);159 when(driver.findElement(rootElementBy))160 .thenReturn(rootElement);161 final ElementLocator locator = newLocator(driver, f);162 final WebElement returnedElement = locator.findElement();163 assertEquals(element, returnedElement);164 }165 @Test166 void shouldUseFindAllByAnnotationsWherePossible() throws Exception {167 final Field f = Block.class.getDeclaredField("listById");168 final By by = By.id("foo");169 final WebElement element1 = mock(WebElement.class, "webElement1");170 final WebElement element2 = mock(WebElement.class, "webElement2");171 final List<WebElement> list = Arrays.asList(element1, element2);172 final WebElement rootElement = mock(WebElement.class);173 when(rootElement.findElements(by))174 .thenReturn(list);175 final WebDriver driver = mock(WebDriver.class);176 when(driver.findElement(rootElementBy))177 .thenReturn(rootElement);178 final ElementLocator locator = newLocator(driver, f);179 final List<WebElement> returnedList = locator.findElements();180 assertEquals(list, returnedList);181 }182 @Test183 void shouldNotMaskNoSuchElementExceptionIfThrownOnRootElement() throws Exception {184 final Field f = Block.class.getDeclaredField("byId");185 final By reBy = By.id("re");186 final WebDriver driver = mock(WebDriver.class);187 when(driver.findElement(reBy)).thenThrow(new NoSuchElementException("rootElement"));188 final ElementLocator locator = newLocator(driver, f);189 try {190 locator.findElement();191 fail("Should have allowed the exception to bubble up from the rootElement");192 } catch (final NoSuchElementException e) {193 /​/​ This is expected...

Full Screen

Full Screen
copy

Full Screen

...55 final By by = new ByIdOrName("list");56 final WebElement element1 = mock(WebElement.class, "webElement1");57 final WebElement element2 = mock(WebElement.class, "webElement2");58 final List<WebElement> list = Arrays.asList(element1, element2);59 when(driver.findElements(by)).thenReturn(list);60 ElementLocator locator = newLocator(driver, f);61 List<WebElement> returnedList = locator.findElements();62 assertThat(returnedList).isEqualTo(list);63 }64 @Test65 public void cachedElementShouldBeCached() throws Exception {66 Field f = Page.class.getDeclaredField("cached");67 final WebDriver driver = mock(WebDriver.class);68 final By by = new ByIdOrName("cached");69 final WebElement element = mock(WebElement.class);70 when(driver.findElement(by)).thenReturn(element);71 ElementLocator locator = newLocator(driver, f);72 locator.findElement();73 locator.findElement();74 verify(driver, times(1)).findElement(by);75 }76 @Test77 public void cachedElementListShouldBeCached() throws Exception {78 Field f = Page.class.getDeclaredField("cachedList");79 final WebDriver driver = mock(WebDriver.class);80 final By by = new ByIdOrName("cachedList");81 final WebElement element1 = mock(WebElement.class, "webElement1");82 final WebElement element2 = mock(WebElement.class, "webElement2");83 final List<WebElement> list = Arrays.asList(element1, element2);84 when(driver.findElements(by)).thenReturn(list);85 ElementLocator locator = newLocator(driver, f);86 locator.findElements();87 locator.findElements();88 verify(driver, times(1)).findElements(by);89 }90 @Test91 public void shouldNotCacheNormalElement() throws Exception {92 Field f = Page.class.getDeclaredField("first");93 final WebDriver driver = mock(WebDriver.class);94 final By by = new ByIdOrName("first");95 final WebElement element = mock(WebElement.class);96 when(driver.findElement(by)).thenReturn(element);97 ElementLocator locator = newLocator(driver, f);98 locator.findElement();99 locator.findElement();100 verify(driver, times(2)).findElement(by);101 }102 @Test103 public void shouldNotCacheNormalElementList() throws Exception {104 Field f = Page.class.getDeclaredField("list");105 final WebDriver driver = mock(WebDriver.class);106 final By by = new ByIdOrName("list");107 final WebElement element1 = mock(WebElement.class, "webElement1");108 final WebElement element2 = mock(WebElement.class, "webElement2");109 final List<WebElement> list = Arrays.asList(element1, element2);110 when(driver.findElements(by)).thenReturn(list);111 ElementLocator locator = newLocator(driver, f);112 locator.findElements();113 locator.findElements();114 verify(driver, times(2)).findElements(by);115 }116 @Test117 public void shouldUseFindByAnnotationsWherePossible() throws Exception {118 Field f = Page.class.getDeclaredField("byId");119 final WebDriver driver = mock(WebDriver.class);120 final By by = By.id("foo");121 final WebElement element = mock(WebElement.class);122 when(driver.findElement(by)).thenReturn(element);123 ElementLocator locator = newLocator(driver, f);124 locator.findElement();125 }126 @Test127 public void shouldUseFindAllByAnnotationsWherePossible() throws Exception {128 Field f = Page.class.getDeclaredField("listById");129 final WebDriver driver = mock(WebDriver.class);130 final By by = By.id("foo");131 final WebElement element1 = mock(WebElement.class, "webElement1");132 final WebElement element2 = mock(WebElement.class, "webElement2");133 final List<WebElement> list = Arrays.asList(element1, element2);134 when(driver.findElements(by)).thenReturn(list);135 ElementLocator locator = newLocator(driver, f);136 locator.findElements();137 }138 @Test139 public void shouldNotMaskNoSuchElementExceptionIfThrown() throws Exception {140 Field f = Page.class.getDeclaredField("byId");141 final WebDriver driver = mock(WebDriver.class);142 final By by = By.id("foo");143 when(driver.findElement(by)).thenThrow(new NoSuchElementException("Foo"));144 ElementLocator locator = newLocator(driver, f);145 assertThatExceptionOfType(NoSuchElementException.class)146 .isThrownBy(locator::findElement);147 }148 @Test149 public void shouldWorkWithCustomAnnotations() {150 final WebDriver driver = mock(WebDriver.class);...

Full Screen

Full Screen
copy

Full Screen

...94 * Locating elements by ALL95 */​96 @Test97 public void locatingByAll() {98 List<WebElement> loginElements = driver.findElements(new ByAll(By.id("txtUsername"),99 By.name("txtPassword"),100 By.name("Submit")));101 for (WebElement element : loginElements){102 System.out.println("Name " + element.getAttribute("name"));103 }104 }105 /​**106 * Locating elements by Chained107 */​108 @Test109 public void locatingByChained() {110 List<WebElement> loginElements = driver.findElements(new ByChained(By.id("frmLogin"),111 By.xpath("/​/​input[@type='text']")));112 for (WebElement element : loginElements) {113 System.out.println("Name " + element.getAttribute("name"));114 }115 }116 /​**117 * Locating elements by Custom locator118 */​119 @Test120 public void locatingByCustomLocator() {121 /​/​Type username122 driver.findElement(new ByAttribute("name", "txtUsername")).sendKeys("Admin");123 /​/​Type password124 driver.findElement(By.id("txtPassword")).sendKeys("Ptl@#321");125 /​/​Click the login button126 driver.findElement(By.id("btnLogin")).click();127 }128 private class ByAttribute extends By {129 private final String attribute;130 private final String value;131 public ByAttribute(String attribute, String value) {132 this.attribute = attribute;133 this.value = value;134 }135 public WebElement findElement(SearchContext searchContext) {136 return searchContext.findElement(By.cssSelector(137 String.format("[%s='%s']", this.attribute, this.value)138 ));139 }140 @Override141 public List<WebElement> findElements(SearchContext searchContext) {142 return searchContext.findElements(By.cssSelector(143 String.format("[%s='%s']", this.attribute, this.value)144 ));145 }146 }147}...

Full Screen

Full Screen
copy

Full Screen

...38 /​/​ support classes39 @Test40 public void canSelectAnOptionUsingSelect(){41 final WebElement selectMenu = driver.findElement(By.id("select-menu"));42 final List<WebElement> options = selectMenu.findElements(By.tagName("option"));43 options.get(2).click(); /​/​ select option 344 final Long selectedIndex = (Long) ((JavascriptExecutor) driver).45 executeScript("return arguments[0].selectedIndex;",46 selectMenu);47 Assertions.assertEquals("3",48 options.get(selectedIndex.intValue()).49 getAttribute("value"));50 }51 @Test52 public void findInstructionsByIdOrName(){53 /​/​ findElement returns the element with the id if it exists, and if not searches for it via the name54 final WebElement instructionsPara = driver.findElement(55 new ByIdOrName("instruction-text"));56 final List<WebElement> instructionsParaAgain = driver.findElements(57 new ByIdOrName("instructions"));58 Assertions.assertEquals(instructionsPara.getText(),59 instructionsParaAgain.get(0).getText());60 }61 @Test62 public void quotesEscapingToCreateXPath(){63 Assertions.assertEquals("\"literal\"",64 Quotes.escape("literal"));65 Assertions.assertEquals("\"'single-quoted'\"",66 Quotes.escape("'single-quoted'"));67 Assertions.assertEquals("'\"double-quoted\"'",68 Quotes.escape("\"double-quoted\""));69 Assertions.assertEquals("concat(\"\", '\"', \"quot'end\", '\"')",70 Quotes.escape("\"quot'end\""));...

Full Screen

Full Screen
copy

Full Screen

...42 /​/​ and the assertions should pass43 WebElement button = driver.findElement( new ByIdOrName("resend-select"));44 Assertions.assertEquals(idButton, button);45 Assertions.assertNotEquals(namedButton, button);46 /​/​ByIdOrName findElements returns all id and name matches47 /​/​findElements for "resend-select" should find 2 buttons48 List<WebElement> buttons = driver.findElements(new ByIdOrName("resend-select"));49 Assertions.assertEquals(2, buttons.size());50 /​/​ the elements identified should be the same as we found initially51 Assertions.assertTrue(buttons.contains(idButton));52 Assertions.assertTrue(buttons.contains(namedButton));53 }54 @Test55 public void byAll(){56 /​/​ we could use ByAll to find by id or by name57 /​/​ by all is a collator, so given a number of locators, find all items that match58 final List<WebElement> buttons = driver.findElements(59 new ByAll(By.id("resend-select"), By.name("resend-select")));60 Assertions.assertEquals(2, buttons.size());61 Assertions.assertTrue(buttons.contains(driver.findElement(By.id("resend-select"))));62 Assertions.assertTrue(buttons.contains(driver.findElement(By.name("resend-select"))));63 }64 @Test65 public void byChained(){66 final WebElement resendSingle = driver.findElement(By.id("resend-select"));67 resendSingle.click();68 resendSingle.click();69 resendSingle.click();70 resendSingle.click();71 final WebElement resend = driver.findElement(By.id("resend-multi"));72 resend.click();73 resend.click();74 /​/​ TODO: make this more specific to only find messages under a 'list'75 final List<WebElement> allMessages = driver.findElements(new ByChained(By.name("list"), By.className("messages")));76 Assertions.assertEquals(6, allMessages.size());77 /​/​ then just the #single list .message78 List<WebElement> singleMessages = driver.findElements(new ByChained(By.id("single-list"),79 By.name("list"), By.className("messages")));80 Assertions.assertEquals(4, singleMessages.size());81 /​/​ then the #multi list .message82 List<WebElement> multiMessages = driver.findElements(new ByChained(By.id("multi-list"), By.name("list"),83 By.className("messages")));84 Assertions.assertEquals(3, multiMessages.size());85 }86 @AfterAll87 public static void closeDriver(){88 driver.quit();89 }90}...

Full Screen

Full Screen
copy

Full Screen

...27 Assert.assertEquals("Resend Multi Option Message",nameButton.getText());28 WebElement button=driver.findElement(new ByIdOrName("resend-select"));29 Assert.assertEquals(idButton,button);30 Assert.assertEquals(nameButton,button);31 /​/​ ByIdOrName findElements returns all id and name matches32 List<WebElement> buttons = driver.findElements(new ByIdOrName("resend-select"));33 Assert.assertTrue(buttons.contains(nameButton));34}35@Test36 public void byAll(){37 List<WebElement> buttons = driver.findElements(new ByAll(By.id("resend-select"),By.name("resend-select")));38}39@Test40 public void byAllChained(){41 final WebElement resendSingle=driver.findElement(By.id("resend-select"));42 resendSingle.click();43 resendSingle.click();44 resendSingle.click();45 resendSingle.click();46 final WebElement resend=driver.findElement(By.id("resend-multi"));47 resend.click();48 resend.click();49 /​/​TODO:make this more specific to only find messages under a 'list'50 /​/​we are building up a chain of locators51 final List<WebElement> allMessages=driver.findElements(new ByChained(By.name("list"),By.className("message")));52Assert.assertEquals(6,allMessages.size());53/​/​then just single message list54 final List<WebElement> singleMessages=driver.findElements(new ByChained(By.id("single"),By.name("list"),By.className("message")));55 final List<WebElement> multiMessages1=driver.findElements(new ByChained(By.id("multi"),By.name("list"),By.className("message")));56 Assert.assertEquals(4,singleMessages.size());57 Assert.assertEquals(2,multiMessages1.size());58}59}...

Full Screen

Full Screen

findElements

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.By;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.WebElement;4import org.openqa.selenium.chrome.ChromeDriver;5import org.openqa.selenium.support.ByIdOrName;6import org.openqa.selenium.support.ui.ExpectedConditions;7import org.openqa.selenium.support.ui.WebDriverWait;8import java.util.List;9import java.util.concurrent.TimeUnit;10public class ByIdOrNameExample {11public static void main(String[] args) {12System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");13WebDriver driver = new ChromeDriver();14driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);15List<WebElement> elements = driver.findElements(new ByIdOrName("firstname"));16System.out.println("Number of elements:" + elements.size());17elements.get(0).sendKeys("Lakshmi");18elements.get(1).sendKeys("K");19driver.close();20}21}22List<WebElement> elements = driver.findElements(By.tagName("tagname"));23import org.openqa.selenium.By;24import org.openqa.selenium.WebDriver;25import org.openqa.selenium.WebElement;26import org.openqa.selenium.chrome.ChromeDriver;27import org.openqa.selenium.support.ui.ExpectedConditions;28import org.openqa.selenium.support.ui.WebDriverWait;29import java.util.List;30import java.util.concurrent.TimeUnit;31public class ByTagNameExample {32public static void main(String[] args) {33System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");34WebDriver driver = new ChromeDriver();35driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);36List<WebElement> elements = driver.findElements(By.tagName("input"));

Full Screen

Full Screen

findElements

Using AI Code Generation

copy

Full Screen

1[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ selenium-java ---2[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ selenium-java ---3[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ selenium-java ---4[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ selenium-java ---5[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ selenium-java ---6[INFO] --- maven-install-plugin:2.4:install (default-install) @ selenium-java ---

Full Screen

Full Screen

findElements

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.By;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.WebElement;4import org.openqa.selenium.chrome.ChromeDriver;5import org.openqa.selenium.support.ByIdOrName;6import org.openqa.selenium.support.pagefactory.ByAll;7import org.openqa.selenium.support.pagefactory.ByChained;8import java.util.List;9public class FindElementsByIdOrName {10 public static void main(String[] args) {11 System.setProperty("webdriver.chrome.driver", "C:\\Users\\Admin\\Downloads\\chromedriver_win32\\chromedriver.exe");12 WebDriver driver = new ChromeDriver();13 List<WebElement> elements = new ByIdOrName("user-message").findElements(driver);14 System.out.println("Size of the list: " + elements.size());15 driver.quit();16 }17}18new ByAll(locator1, locator2, …);19import org.openqa.selenium.By;20import org.openqa.selenium.WebDriver;21import org.openqa.selenium.WebElement;22import org.openqa.selenium.chrome.ChromeDriver;23import org.openqa.selenium.support.ByAll;24import java.util.List;25public class FindElementsByAll {26 public static void main(String[] args) {27 System.setProperty("webdriver.chrome.driver", "C:\\Users\\Admin\\Downloads\\chromedriver_win32\\chromedriver.exe");28 WebDriver driver = new ChromeDriver();29 List<WebElement> elements = new ByAll(By.id("user-message"), By.name("user-message")).findElements(driver);30 System.out.println("Size of the list: " + elements.size());31 driver.quit();32 }33}34new ByChained(locator1, locator2, …);

Full Screen

Full Screen

findElements

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.By;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.WebElement;4import org.openqa.selenium.firefox.FirefoxDriver;5import org.openqa.selenium.support.ByIdOrName;6import java.util.List;7public class FindElementsByIdOrName {8 public static void main(String[] args) {9 WebDriver driver = new FirefoxDriver();10 List<WebElement> elements = new ByIdOrName("lst-ib").findElements(driver);11 System.out.println("Number of elements found: " + elements.size());12 for (WebElement element : elements) {13 System.out.println("Element text: " + element.getText());14 }15 driver.quit();16 }17}

Full Screen

Full Screen

findElements

Using AI Code Generation

copy

Full Screen

1package com.testautomationguru.ocular.examples;2import org.openqa.selenium.By;3import org.openqa.selenium.WebDriver;4import org.openqa.selenium.WebElement;5import org.openqa.selenium.firefox.FirefoxDriver;6import org.openqa.selenium.support.ByIdOrName;7import java.util.List;8public class ByIdOrNameTest {9public static void main(String[] args) {10WebDriver driver = new FirefoxDriver();11List<WebElement> elements = new ByIdOrName("s").findElements(driver);12System.out.println("Number of elements found by id or name: " + elements.size());13driver.quit();14}15}16package com.testautomationguru.ocular.examples;17import org.openqa.selenium.By;18import org.openqa.selenium.WebDriver;19import org.openqa.selenium.WebElement;20import org.openqa.selenium.firefox.FirefoxDriver;21import org.openqa.selenium.support.ByIdOrName;22import java.util.List;23import org.testng.Assert;24import org.testng.annotations.AfterTest;25import org.testng.annotations.BeforeTest;26import org.testng.annotations.Test;27public class ByIdOrNameTest {28WebDriver driver;29public void setup() {30driver = new FirefoxDriver();31}32public void testFindElementsByIdOrName() {33List<WebElement> elements = new ByIdOrName("s").findElements(driver);34System.out.println("Number of elements found by id or name: " + elements.size());35Assert.assertEquals(elements.size(), 1);36}37public void teardown() {38driver.quit();39}40}

Full Screen

Full Screen

StackOverFlow community discussions

Questions
Discussion

What is JavaScriptExecutor in Selenium?

Selenium - how to find elements by attribute with any value in Java?

Hover over on element and wait with Selenium WebDriver using Java

Element is not clickable at point . Other element would receive the click:

How to switch to the new browser window, which opens after click on the button?

How to explicitly wait while using page factory in Selenium?

Should we write separate page-object for pop-up with a selection drop-down?

Selenium web driver: cannot be scrolled into view

ChromeDriver - Disable developer mode extensions pop up on Selenium WebDriver automation

finding element by classname and tagname using selenium webdriver

JavascriptExecutor

JavascriptExecutor is the Selenium interface which is being implemented by all the following classes:

  • FirefoxDriver
  • ChromeDriver
  • InternetExplorerDriver
  • EdgeDriver
  • OperaDriver
  • SafariDriver
  • RemoteWebDriver
  • EventFiringWebDriver
  • HtmlUnitDriver

While you execute your Selenium script at times because of cross domain policies browsers enforce your script execution may fail unexpectedly and without adequate error logging. This is particularly pertinent when creating your own XHR request or when trying to access another frame.

You will find a detailed discussion in Uncaught DOMException: Blocked a frame with origin “http://localhost:8080” from accessing a cross-origin frame while listing the iframes in page

JavascriptExecutor interface provides two methods as follows:

  • executeScript(): This method executes JavaScript in the context of the currently selected frame or window. The script fragment provided will be executed as the body of an anonymous function. Within the script you need to use document to refer to the current document. Note that local variables will not be available once the script has finished executing, though global variables will persist.

  • executeAsyncScript(): This method executes an asynchronous piece of JavaScript in the context of the currently selected frame or window. Unlike executing synchronous JavaScript, scripts executed with this method must explicitly signal they are finished by invoking the provided callback. This callback is always injected into the executed function as the last argument.


Example

A couple of examples:


Reference

You also can find a couple of detailed discussions about the arguments in:


tl;dr

Cross-domain policy file specification

https://stackoverflow.com/questions/52689880/what-is-javascriptexecutor-in-selenium

Blogs

Check out the latest blogs from LambdaTest on this topic:

8 Actionable Insights To Write Better Automation Code

As you start on with automation you may come across various approaches, techniques, framework and tools you may incorporate in your automation code. Sometimes such versatility leads to greater complexity in code than providing better flexibility or better means of resolving issues. While writing an automation code it’s important that we are able to clearly portray our objective of automation testing and how are we achieving it. Having said so it’s important to write ‘clean code’ to provide better maintainability and readability. Writing clean code is also not an easy cup of tea, you need to keep in mind a lot of best practices. The below topic highlights 8 silver lines one should acquire to write better automation code.

Test a SignUp Page: Problems, Test Cases, and Template

Every user journey on a website starts from a signup page. Signup page is one of the simplest yet one of the most important page of the website. People do everything in their control to increase the conversions on their website by changing signup pages, modifying them, performing A/B testing to find out the best pages and what not. But the major problem that went unnoticed or is usually underrated is testing the signup page. If you try all the possible hacks but fail to test it properly you’re missing on a big thing. Because if users are facing problem while signing up they leave your website and will never come back.

JUnit Automation Testing With Selenium

This article is a part of our Content Hub. For more in-depth resources, check out our content hub on JUnit Tutorial.

What Is Cross Browser Compatibility And Why We Need It?

This article is a part of our Content Hub. For more in-depth resources, check out our content hub on Cross Browser Testing Tutorial.

How Agile Teams Use Test Pyramid for Automation?

Product testing is considered a very important step before the product is released to the end customer. Depending on the nature and complexity of the project/product, you need to make sure that you use the very best of testing methodologies (manual testing, smoke testing, UI testing, automation testing, etc.) in order to unearth bugs and improve product quality with each release.

Selenium 4 Tutorial:

LambdaTest’s Selenium 4 tutorial is covering every aspects of Selenium 4 testing with examples and best practices. Here you will learn basics, such as how to upgrade from Selenium 3 to Selenium 4, to some advanced concepts, such as Relative locators and Selenium Grid 4 for Distributed testing. Also will learn new features of Selenium 4, such as capturing screenshots of specific elements, opening a new tab or window on the browser, and new protocol adoptions.

Chapters:

  1. Upgrading From Selenium 3 To Selenium 4?: In this chapter, learn in detail how to update Selenium 3 to Selenium 4 for Java binding. Also, learn how to upgrade while using different build tools such as Maven or Gradle and get comprehensive guidance for upgrading Selenium.

  2. What’s New In Selenium 4 & What’s Being Deprecated? : Get all information about new implementations in Selenium 4, such as W3S protocol adaption, Optimized Selenium Grid, and Enhanced Selenium IDE. Also, learn what is deprecated for Selenium 4, such as DesiredCapabilites and FindsBy methods, etc.

  3. Selenium 4 With Python: Selenium supports all major languages, such as Python, C#, Ruby, and JavaScript. In this chapter, learn how to install Selenium 4 for Python and the features of Python in Selenium 4, such as Relative locators, Browser manipulation, and Chrom DevTool protocol.

  4. Selenium 4 Is Now W3C Compliant: JSON Wireframe protocol is retiring from Selenium 4, and they are adopting W3C protocol to learn in detail about the advantages and impact of these changes.

  5. How To Use Selenium 4 Relative Locator? : Selenium 4 came with new features such as Relative Locators that allow constructing locators with reference and easily located constructors nearby. Get to know its different use cases with examples.

  6. Selenium Grid 4 Tutorial For Distributed Testing: Selenium Grid 4 allows you to perform tests over different browsers, OS, and device combinations. It also enables parallel execution browser testing, reads up on various features of Selenium Grid 4 and how to download it, and runs a test on Selenium Grid 4 with best practices.

  7. Selenium Video Tutorials: Binge on video tutorials on Selenium by industry experts to get step-by-step direction from automating basic to complex test scenarios with Selenium.

Selenium 101 certifications:

LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.

Run Selenium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in ByIdOrName

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful