Run Selenium automation tests on LambdaTest cloud grid
Perform automation testing on 3000+ real desktop and mobile devices online.
package com.tls.liferaylms.test;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.ElementNotVisibleException;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import com.gargoylesoftware.htmlunit.ElementNotFoundException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.tls.liferaylms.test.util.Context;
import com.tls.liferaylms.test.util.Sleep;
public class SeleniumTestCase {
protected WebDriver driver;
protected String baseUrl;
private Log log = null;
private boolean acceptNextAlert = true;
@Before
public void setUp() throws Exception {
driver = SeleniumDriverUtil.getDriver();
baseUrl = Context.getBaseUrl();
}
@After
public void tearDown() throws Exception {
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
} catch (ElementNotVisibleException e) {
return false;
} catch (ElementNotFoundException e) {
return false;
} catch (Exception e) {
return false;
}
}
public WebElement getElement(By by){
try {
// Sleep.waitFor(by, driver);
return driver.findElement(by);
} catch(TimeoutException e){
return driver.findElement(by);
} catch (NoSuchElementException e) {
return null;
} catch (ElementNotVisibleException e) {
return null;
} catch (ElementNotFoundException e) {
return null;
} catch (Exception e) {
return null;
}
}
public WebElement getElement(WebElement we,By by){
try {
// Sleep.waitFor(by, driver);
return we.findElement(by);
} catch(TimeoutException e){
return we.findElement(by);
} catch (NoSuchElementException e) {
return null;
} catch (ElementNotVisibleException e) {
return null;
} catch (ElementNotFoundException e) {
return null;
} catch (Exception e) {
return null;
}
}
public List<WebElement> getElements(WebElement we,By by){
try {
return we.findElements(by);
} catch (NoSuchElementException e) {
return null;
} catch (ElementNotVisibleException e) {
return null;
} catch (ElementNotFoundException e) {
return null;
} catch (Exception e) {
return null;
}
}
public List<WebElement> getElements(By by){
try {
return driver.findElements(by);
} catch (NoSuchElementException e) {
return null;
} catch (ElementNotVisibleException e) {
return null;
} catch (ElementNotFoundException e) {
return null;
} catch (Exception e) {
return null;
}
}
public boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
public String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
public Log getLog(){
if(log==null){
log = LogFactoryUtil.getLog(this.getClass());
}
return log;
}
/** Get the current line number.
* @return String - Current line number.
*/
public String getLineNumber() {
return ". At line ".concat(String.valueOf(Thread.currentThread().getStackTrace()[2].getLineNumber()));
}
}
package ToolsQA.MavenDemo;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.ElementNotVisibleException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Exceptn {
static By search = By.cssSelector("input[name='h']");
public static void main(String A[]) {
System.setProperty("webdriver.chrome.driver",
"C://Users//srishti.goel//Downloads//chromedriver_win32//chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com");
// WebElement search = driver.findElement(By.id("q"));
waitForElement(driver, search);
driver.findElement(search).sendKeys("hello world");
}
public static void waitForElement(WebDriver driver, By w) {
try {
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
WebDriverWait wait = new WebDriverWait(driver, 2);
// wait.until(ExpectedConditions.visibilityOfElementLocated(w));
//wait.until(ExceptedConditions.)
}
catch (TimeoutException e) {
System.out.println("Timeout exception");
}
catch (NoSuchElementException e) {
System.out.println("No such element exception");
} catch (ElementNotVisibleException e) {
} catch (StaleElementReferenceException e) {
}
}
}
package github.isanjeevkumar.selenium;
import java.time.Duration;
import java.util.NoSuchElementException;
import com.google.common.base.Function;
import org.apache.commons.lang.NotImplementedException;
import org.openqa.selenium.By;
import org.openqa.selenium.ElementNotVisibleException;
import org.openqa.selenium.SearchContext;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ByIdOrName;
import org.openqa.selenium.support.locators.RelativeLocator;
import org.openqa.selenium.support.locators.RelativeLocator.RelativeBy;
import org.openqa.selenium.support.pagefactory.ByChained;
import org.openqa.selenium.support.ui.WebDriverWait;
import github.isanjeevkumar.enums.RelativeByLocator;
public class WebElementFinder {
public static WebElement getElement(WebDriver driver, final By elementLocator, int timeOutInSecs)
throws Exception {
try {
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(timeOutInSecs));
wait.ignoring(NoSuchElementException.class);
wait.ignoring(ElementNotVisibleException.class);
return wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return getElement(driver, elementLocator);
}
});
} catch (Exception ex) {
System.err.println("Error:" + ex.getMessage());
throw ex;
}
}
public static WebElement getElementByIdOrName(WebDriver driver, final String byIdOrName, int timeOutInSecs)
throws Exception {
try {
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(timeOutInSecs));
wait.ignoring(NoSuchElementException.class);
wait.ignoring(ElementNotVisibleException.class);
return wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return getByIdOrName(driver, byIdOrName);
}
});
} catch (Exception ex) {
System.err.println("Error:" + ex.getMessage());
throw ex;
}
}
public static WebElement getElementByChained(WebDriver driver, final ByChained chainedValue, int timeOutInSecs)
throws Exception {
try {
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(timeOutInSecs));
wait.ignoring(NoSuchElementException.class);
wait.ignoring(ElementNotVisibleException.class);
return wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return getByChained(driver, chainedValue);
}
});
} catch (Exception ex) {
System.err.println("Error:" + ex.getMessage());
throw ex;
}
}
public static WebElement getElementByRelativeLocator(WebDriver driver, WebElement referenceElement,
final By elementLocator, RelativeByLocator relativeBy,
int timeOutInSecs)
throws Exception {
try {
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(timeOutInSecs));
wait.ignoring(NoSuchElementException.class);
wait.ignoring(ElementNotVisibleException.class);
return wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return getRelativeElement(driver, referenceElement, elementLocator, relativeBy);
}
});
} catch (Exception ex) {
System.err.println("Error:" + ex.getMessage());
throw ex;
}
}
private static WebElement getElement(final SearchContext searchContext, final By elementLocator) {
WebElement element = searchContext.findElement(elementLocator);
if (element.isDisplayed() && element.isEnabled()) {
return element;
}
throw new ElementNotVisibleException("WebElement with locator " + elementLocator + " is not visible.");
}
private static WebElement getByIdOrName(final SearchContext searchContext, final String elementLocatorValue) {
WebElement element = searchContext.findElement(new ByIdOrName(elementLocatorValue));
if (element.isDisplayed() && element.isEnabled()) {
return element;
}
throw new ElementNotVisibleException("WebElement with locator " + elementLocatorValue + " is not visible.");
}
private static WebElement getByChained(final SearchContext searchContext, final ByChained getByChained) {
WebElement element = searchContext.findElement(getByChained);
if (element.isDisplayed() && element.isEnabled()) {
return element;
}
throw new ElementNotVisibleException("WebElement with locator " + getByChained.toString() + " is not visible.");
}
private static WebElement getRelativeElement(final SearchContext searchContext, WebElement referenceElement,
final By elementLocator, RelativeByLocator relativeLocator) {
RelativeBy relativeBy = RelativeLocator.with(elementLocator);
WebElement element = null;
switch (relativeLocator) {
case ABOVE:
element = searchContext.findElement(relativeBy.above(referenceElement));
break;
case BELOW:
element = searchContext.findElement(relativeBy.below(referenceElement));
break;
case LEFT_OF:
element = searchContext.findElement(relativeBy.toLeftOf(referenceElement));
break;
case NEAR:
element = searchContext.findElement(relativeBy.near(referenceElement));
break;
case RIGHT_OF:
element = searchContext.findElement(relativeBy.toRightOf(referenceElement));
break;
default:
throw new NotImplementedException("relativeLocatorBy is not implemented. Please check.");
}
if (element.isDisplayed() && element.isEnabled()) {
return element;
}
throw new ElementNotVisibleException(
"WebElement with locator " + elementLocator.toString() + " is not visible.");
}
}
public boolean isPrebuiltTestButtonVisible() {
try {
if (preBuiltTestButton.isEnabled()) {
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
try{
if( driver.findElement(By.xpath("//div***")).isDisplayed()){
System.out.println("Element is Visible");
}
}
catch(NoSuchElementException e){
else{
System.out.println("Element is InVisible");
}
}
public boolean isElementExist(By by) {
int count = driver.findElements(by).size();
if (count>=1) {
Logger.LogMessage("isElementExist: " + by + " | Count: " + count, Priority.Medium);
return true;
}
else {
Logger.LogMessage("isElementExist: " + by + " | Could not find element", Priority.High);
return false;
}
}
public boolean isElementNotExist(By by) {
int count = driver.findElements(by).size();
if (count==0) {
Logger.LogMessage("ElementDoesNotExist: " + by, Priority.Medium);
return true;
}
else {
Logger.LogMessage("ElementDoesExist: " + by, Priority.High);
return false;
}
}
public boolean isElementVisible(By by) {
try {
if (driver.findElement(by).isDisplayed()) {
Logger.LogMessage("Element is Displayed: " + by, Priority.Medium);
return true;
}
}
catch(Exception e) {
Logger.LogMessage("Element is Not Displayed: " + by, Priority.High);
return false;
}
return false;
}
public boolean isElementFound( String text) {
try{
WebElement webElement = appiumDriver.findElement(By.xpath(text));
System.out.println("isElementFound : true :"+text + "true");
}catch(NoSuchElementException e){
System.out.println("isElementFound : false :"+text);
return false;
}
return true;
}
text is the xpath which you would be passing when calling the function.
the return value will be true if the element is present else false if element is not pressent
public static boolean isElementVisible(WebElement webElement, int timeOut) {
try {
WebDriverWait wait = new WebDriverWait(driver, timeOut);
wait.until(ExpectedConditions.visibilityOf(webElement));
return true;
} catch (org.openqa.selenium.NoSuchElementException e) {
return false;
}
}
public static boolean isElementVisible(final By by)
throws InterruptedException {
boolean value = false;
if (driver.findElements(by).size() > 0) {
value = true;
}
return value;
}
if (!driver.FindElement(By.Name("newtagfield")).Displayed) //if the tag options is not displayed
driver.FindElement(By.Id("expand-folder-tags")).Click(); //make sure the folder and tags options are visible
assertTrue(isElementPresent(By.id("idOfElement")));
@Test
// visibilityOfElementLocated has been statically imported
public demo(){
By searchButtonSelector = By.className("search_button");
WebDriverWait wait = new WebDriverWait(driver, 10);
driver.get(homeUrl);
WebElement searchButton = wait.until(
visibilityOfElementLocated
(searchButtonSelector));
//clicks the search button
searchButton.click();
export default function isDisplayedInViewport () {
return getBrowserObject(this).execute(isDisplayedInViewportScript, {
[ELEMENT_KEY]: this.elementId, // w3c compatible
ELEMENT: this.elementId // jsonwp compatible
})
}
/**
* check if element is visible and within the viewport
* @param {HTMLElement} elem element to check
* @return {Boolean} true if element is within viewport
*/
export default function isDisplayedInViewport (elem) {
const dde = document.documentElement
let isWithinViewport = true
while (elem.parentNode && elem.parentNode.getBoundingClientRect) {
const elemDimension = elem.getBoundingClientRect()
const elemComputedStyle = window.getComputedStyle(elem)
const viewportDimension = {
width: dde.clientWidth,
height: dde.clientHeight
}
isWithinViewport = isWithinViewport &&
(elemComputedStyle.display !== 'none' &&
elemComputedStyle.visibility === 'visible' &&
parseFloat(elemComputedStyle.opacity, 10) > 0 &&
elemDimension.bottom > 0 &&
elemDimension.right > 0 &&
elemDimension.top < viewportDimension.height &&
elemDimension.left < viewportDimension.width)
elem = elem.parentNode
}
return isWithinViewport
}
/**
* Demo of a java version of webdriverio's isDisplayedInViewport
* https://github.com/webdriverio/webdriverio/blob/v5.0.0-beta.2/packages/webdriverio/src/commands/element/isDisplayedInViewport.js
* The super class GuiTest just deals with setup of the driver and such
*/
class VisibleDemoTest extends GuiTest {
public static String readScript(String name) {
try {
File f = new File("selenium-scripts/" + name + ".js");
BufferedReader reader = new BufferedReader( new FileReader( file ) );
return reader.lines().collect(Collectors.joining(System.lineSeparator()));
} catch(IOError e){
throw new RuntimeError("No such Selenium script: " + f.getAbsolutePath());
}
}
public static Boolean isVisibleInViewport(RemoteElement e){
// according to the Webdriver spec a string that identifies an element
// should be deserialized into the corresponding web element,
// meaning the 'isDisplayedInViewport' function should receive the element,
// not just the string we passed to it originally - how this is done is not our concern
//
// This is probably when ELEMENT and ELEMENT_KEY refers to in the wd.io implementation
//
// Ref https://w3c.github.io/webdriver/#dfn-json-deserialize
return js.executeScript(readScript("isDisplayedInViewport"), e.getId());
}
public static Boolean isVisibleInViewport(String xPath){
driver().findElementByXPath("//button[@id='should_be_visible']");
}
@Test
public demo_isVisibleInViewport(){
// you can build all kinds of abstractions on top of the base method
// to make it more Selenium-ish using retries with timeouts, etc
assertTrue(isVisibleInViewport("//button[@id='should_be_visible']"));
assertFalse(isVisibleInViewport("//button[@id='should_be_hidden']"));
}
}
wait=WebDriverWait(driver,timeout=10,poll_frequency=1)
element=wait.until(element_has_text((By.CSS_SELECTOR,"div#finish>h4"),"Hello World!"))
class element_has_text(object):
"""An expectation for checking that an element has a particular text.
locator - used to find the element
returns the WebElement once it has the particular text
"""
def __init__(self,locator,expected_text):
self.locator=locator
self.expected_text=expected_text
def __call__(self,driver):
element = driver.find_element(*self.locator)
if (element.text==self.expected_text):
return element
else:
return False
element = None
i = 6
while element is None:
try:
wait = WebDriverWait(driver, 5, poll_frequency=1)
element = wait.until(expected_conditions.visibility_of_element_located(el))
except:
driver.refresh()
i = i - 1
print(i)
if i < 0:
raise Exception('Element not found')
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import *
driver = webdriver.Firefox()
# Load some webpage
wait = WebDriverWait(driver, 10, poll_frequency=1, ignored_exceptions=[ElementNotVisibleException, ElementNotSelectableException])
element = wait.until(EC.element_to_be_clickable((By.XPATH, "//div")))
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("your locator value")));
wait.until(ExpectedConditions.ElementIsVisible(By.xpath("your locator value")));
driver.Manage().Window.Size = new System.Drawing.Size(1928, 1060);
public static void Listget (WebDriver driver) throws Exception
{
Thread.sleep(5000);
UtilityMethod.getAppLocaters(driver, "closeicon").click();
Actions action = new Actions(driver);
WebElement we = driver.findElement(By.xpath("//li[@class='parent dropdown aligned-left']"));
Thread.sleep(5000);
action.moveToElement(we).build().perform();
List<WebElement>links = driver.findElements(By.xpath("//span[@class='menu-title']"));
int total_count = links.size();
System.out.println("Total size :=" +total_count);
for(int i=0;i<total_count;i++)
{
WebElement element = links.get(i);
String text = element.getAttribute("innerHTML");
System.out.println("linksnameis:=" +text);
try{
File src = new File("D:ReadFile.xlsx");
FileInputStream fis = new FileInputStream(src);
XSSFWorkbook wb=new XSSFWorkbook(fis);
XSSFSheet sh = wb.getSheetAt(0);
sh.createRow(i).createCell(1).setCellValue(text);
FileOutputStream fos = new FileOutputStream(new File("D:/ReadFile.xlsx"));
wb.write(fos);
fos.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
}
int var_ele_size= driver.findElements(By.xpath("locator")).size();
driver.findElements(By.xpath("locator")).get(var_ele_size-1).click();
By.cssSelector("div.signIn div#_loginButton")
By.cssSelector("form#_loginForm div#_loginButton")
By.xpath("//div[@class='page']//div[@id='_loginButton']")
Accelerate Your Automation Test Cycles With LambdaTest
Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.