Cucumber with Java Selenium framework - java

I am working as a manual tester now recently I shifted to Selenium, in my company now they are telling me to create Cucumber Java Selenium framework for a project from scratch. My requirement is I need to create a class which it consists of all the methods of selenium like, sendKeys, Click, dragAndDrop, mouseHover like that all selenium related actions I need to put in one class...I'm facing very difficulty.
Does anyone have such type of class which has all Selenium actions?

You can use webdriver methods like the following. For the full list please check https://seleniumhq.github.io/selenium/docs/api/rb/method_list.html
get()
getCurrentUrl()
findElement(By, by) and click()
isEnabled()
findElement(By, by) with sendKeys()
findElement(By, by) with getText()
Submit()
findElements(By, by)

You don't need a class with all of those actions; Selenium provides them out of the box. This can be achieved simply by instantiating a new instance of the driver:
WebDriver driver = new ChromeDriver();
And then calling the functions you require:
driver.getElement(By.id("element")).click();
Creating a new class to wrap an existing function is terrible terrible practice. If you're looking for a good design pattern for Selenium tests, look up the 'Page Object Model'.

I hope this methods will be helpful to you
public static void wait(int secs) {
try {
Thread.sleep(1000 * secs);
} catch (InterruptedException e) {
}
}
/**
* Generates the String path to the screenshot taken.
* Within the method, the screenshot is taken and is saved into FileUtils.
* The String return will have a unique name destination of the screenshot itself.
*
* #param name Test name passed in as a String
* #return unique String representation of the file's location / path to file
*/
public static String getScreenshot(String name) {
// name the screenshot with the current date time to avoid duplicate name
//for windows users or if you cannot get a screenshot
String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MMdd_hh_mm_ss_a"));
// TakesScreenshot ---> interface from selenium which takes screenshots
TakesScreenshot ts = (TakesScreenshot) Driver.getDriver();
File source = ts.getScreenshotAs(OutputType.FILE);
// full path to the screenshot location
String target = System.getProperty("user.dir") + "/test-output/Screenshots/" + name + date + ".png";
//if screenshot doesn't work
//try to provide hardcoded path
// String target = "/Users/studio2/IdeaProjects/Spring2019FinalTestNGFramework/screenshots/" + name + date + ".png";
File finalDestination = new File(target);
// save the screenshot to the path given
try {
FileUtils.copyFile(source, finalDestination);
} catch (IOException e) {
e.printStackTrace();
}
return target;
}
/*
* switches to new window by the exact title
* returns to original window if windows with given title not found
*/
public static void switchToWindow(String targetTitle) {
String origin = Driver.getDriver().getWindowHandle();
for (String handle : Driver.getDriver().getWindowHandles()) {
Driver.getDriver().switchTo().window(handle);
if (Driver.getDriver().getTitle().equals(targetTitle)) {
return;
}
}
Driver.getDriver().switchTo().window(origin);
}
public static void hover(WebElement element) {
Actions actions = new Actions(Driver.getDriver());
actions.moveToElement(element).perform();
}
/**
* return a list of string from a list of elements
* text
*
* #param list of webelements
* #return
*/
public static List<String> getElementsText(List<WebElement> list) {
List<String> elemTexts = new ArrayList<>();
for (WebElement el : list) {
if (!el.getText().isEmpty()) {
elemTexts.add(el.getText());
}
}
return elemTexts;
}
/**
* Extracts text from list of elements matching the provided locator into new List<String>
*
* #param locator
* #return list of strings
*/
public static List<String> getElementsText(By locator) {
List<WebElement> elems = Driver.getDriver().findElements(locator);
List<String> elemTexts = new ArrayList<>();
for (WebElement el : elems) {
if (!el.getText().isEmpty()) {
elemTexts.add(el.getText());
}
}
return elemTexts;
}
public static WebElement waitForVisibility(WebElement element, int timeToWaitInSec) {
WebDriverWait wait = new WebDriverWait(Driver.getDriver(), timeToWaitInSec);
return wait.until(ExpectedConditions.visibilityOf(element));
}
public static WebElement waitForVisibility(By locator, int timeout) {
WebDriverWait wait = new WebDriverWait(Driver.getDriver(), timeout);
return wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
}
public static WebElement waitForClickability(WebElement element, int timeout) {
WebDriverWait wait = new WebDriverWait(Driver.getDriver(), timeout);
return wait.until(ExpectedConditions.elementToBeClickable(element));
}
public static WebElement waitForClickability(By locator, int timeout) {
WebDriverWait wait = new WebDriverWait(Driver.getDriver(), timeout);
return wait.until(ExpectedConditions.elementToBeClickable(locator));
}
public static Boolean waitForURL(String actualURL, int timeout) {
WebDriverWait wait = new WebDriverWait(Driver.getDriver(), 5);
return wait.until(ExpectedConditions.urlToBe(actualURL));
}
public static void waitForPageToLoad(long timeOutInSeconds) {
ExpectedCondition<Boolean> expectation = new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("complete");
}
};
try {
Logger logger = Logger.getLogger(UtilsBrowser.class);
logger.info("Waiting for page to load...");
WebDriverWait wait = new WebDriverWait(Driver.getDriver(), timeOutInSeconds);
wait.until(expectation);
} catch (Throwable error) {
System.out.println(
"Timeout waiting for Page Load Request to complete after " + timeOutInSeconds + " seconds");
}
}
public static WebElement fluentWait(final WebElement webElement, int timeinsec) {
FluentWait<WebDriver> wait = new FluentWait<WebDriver>(Driver.getDriver())
.withTimeout(Duration.ofSeconds(timeinsec))
.pollingEvery(Duration.ofMillis(500))
.ignoring(NoSuchElementException.class);
WebElement element = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return webElement;
}
});
return element;
}
/**
* Verifies whether the element matching the provided locator is displayed on page
*
* #param by
* #throws AssertionError if the element matching the provided locator is not found or not displayed
*/
public static void verifyElementDisplayed(By by) {
try {
assertTrue("Element not visible: " + by, Driver.getDriver().findElement(by).isDisplayed());
} catch (NoSuchElementException e) {
e.printStackTrace();
Assert.fail("Element not found: " + by);
}
}
/**
* Verifies whether the element matching the provided locator is NOT displayed on page
*
* #param by
* #throws AssertionError the element matching the provided locator is displayed
*/
public static void verifyElementNotDisplayed(By by) {
try {
Assert.assertFalse("Element should not be visible: " + by, Driver.getDriver().findElement(by).isDisplayed());
} catch (NoSuchElementException e) {
e.printStackTrace();
}
}
/**
* Verifies whether the element is displayed on page
*
* #param element
* #throws AssertionError if the element is not found or not displayed
*/
public static void verifyElementDisplayed(WebElement element) {
try {
assertTrue("Element not visible: " + element, element.isDisplayed());
} catch (NoSuchElementException e) {
e.printStackTrace();
Assert.fail("Element not found: " + element);
}
}
/**
* Waits for element to be not stale
*
* #param element
*/
public void waitForStaleElement(WebElement element) {
int y = 0;
while (y <= 15) {
if (y == 1)
try {
element.isDisplayed();
break;
} catch (StaleElementReferenceException st) {
y++;
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (WebDriverException we) {
y++;
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/**
* Selects a random value from a dropdown list and returns the selected Web Element
*
* #param select
* #return
*/
public static WebElement selectRandomTextFromDropdown(Select select) {
Random random = new Random();
List<WebElement> weblist = select.getOptions();
int optionIndex = 1 + random.nextInt(weblist.size() - 1);
select.selectByIndex(optionIndex);
return select.getFirstSelectedOption();
}
/**
* Clicks on an element using JavaScript
*
* #param element
*/
public void clickWithJS(WebElement element) {
((JavascriptExecutor) Driver.getDriver()).executeScript("arguments[0].scrollIntoView(true);", element);
((JavascriptExecutor) Driver.getDriver()).executeScript("arguments[0].click();", element);
}
/**
* Scrolls down to an element using JavaScript
*
* #param element
*/
public void scrollToElement(WebElement element) {
((JavascriptExecutor) Driver.getDriver()).executeScript("arguments[0].scrollIntoView(true);", element);
}
/**
* Performs double click action on an element
*
* #param element
*/
public void doubleClick(WebElement element) {
new Actions(Driver.getDriver()).doubleClick(element).build().perform();
}
/**
* Changes the HTML attribute of a Web Element to the given value using JavaScript
*
* #param element
* #param attributeName
* #param attributeValue
*/
public void setAttribute(WebElement element, String attributeName, String attributeValue) {
((JavascriptExecutor) Driver.getDriver()).executeScript("arguments[0].setAttribute(arguments[1], arguments[2]);", element, attributeName, attributeValue);
}
public String[] fromListToString(List<WebElement> x) {
String[] trans = new String[x.size()];
for (WebElement xx : x) {
int count = 0;
trans[count] = xx.getText();
count++;
}
Arrays.sort(trans);
return trans;
}
/**
* Highlighs an element by changing its background and border color
*
* #param element
*/
public static void highlight(WebElement element) {
((JavascriptExecutor) Driver.getDriver()).executeScript("arguments[0].setAttribute('style', 'background: yellow; border: 2px solid red;');", element);
wait(1);
((JavascriptExecutor) Driver.getDriver()).executeScript("arguments[0].removeAttribute('style', 'background: yellow; border: 2px solid red;');", element);
}
/**
* Checks or unchecks given checkbox
*
* #param element
* #param check
*/
public static void selectCheckBox(WebElement element, boolean check) {
if (check) {
if (!element.isSelected()) {
element.click();
}
} else {
if (element.isSelected()) {
element.click();
}
}
}
public static void grabHold(WebDriver driver) {
/* /NOTE: Be sure to set -> String parentHandle=driver.getWindowHandle(); prior to the action preceding method deployment */
String parentHandle = driver.getWindowHandle();
Set<String> windows = driver.getWindowHandles();
for (String window : windows) {
if (window != parentHandle)
driver.switchTo().window(window);
}
}
public static void waitUntilTitleEquals(int timeout, String x) {
WebDriverWait wait = new WebDriverWait(Driver.getDriver(), timeout);
wait.until(ExpectedConditions.titleContains(x));
}
public static int getRandomNumInRange(int low, int high) {
Random random = new Random();
return random.nextInt(high - low) + low;
}
public void waitForPresenceOfElementByCss(String css) {
WebDriverWait wait = new WebDriverWait(Driver.getDriver(),
Long.parseLong(ConfigurationReader.getProperties("timeout")));
wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(css)));
}
public void hitEnterUsingRobot() {
Robot rb;
try {
rb = new Robot();
rb.keyPress(KeyEvent.VK_ENTER);
rb.keyRelease(KeyEvent.VK_ENTER);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public boolean verifyAlertPresent() {
try {
Driver.getDriver().switchTo().alert();
return true;
} catch (NoAlertPresentException Ex) {
// System.out.println("Alert is not presenet");
}
return false;
}
public boolean isElementVisible(By arg0) {
boolean elementVisible = false;
try {
(new WebDriverWait(Driver.getDriver(), 60)).until(ExpectedConditions.visibilityOfElementLocated(arg0));
elementVisible = true;
} catch (TimeoutException ex) {
elementVisible = false;
}
return elementVisible;
}
public static boolean isElementNotVisible(By arg0) {
boolean elementVisible = false;
try {
//these two waitinf for webelement to be gone
// (new WebDriverWait(Driver.getDriver(), 60)).until(ExpectedConditions.invisibilityOfElementLocated(arg0));
(new WebDriverWait(Driver.getDriver(), 60)).until(ExpectedConditions.not(ExpectedConditions.presenceOfAllElementsLocatedBy(arg0)));
elementVisible = true;
} catch (NullPointerException ex) {
elementVisible = false;
}
return elementVisible;
}

Related

Can't make Actions.class methods work unless driver instance declared in #Test

I'm new to Selenium & new to Java as well. So maybe I'm missing something obvious, but I’m spinning on this for a while now, can't move forward & totally desperate. Please help!
Here is my set-up:
My custom Driver class implements WebDriver & sets property:
public class Driver implements WebDriver {
private WebDriver driver;
private String browserName;
public Driver(String browserName) throws Exception {
this.browserName = browserName;
if(browserName.equalsIgnoreCase("chrome")) {
System.setProperty("webdriver.chrome.driver", "src/test/resources/chromedriver");
this.driver = new ChromeDriver();
}
else if(browserName.equalsIgnoreCase("firefox")) {
System.setProperty("webdriver.gecko.driver", "src/test/resources/geckodriver");
this.driver = new FirefoxDriver();
}
else {
throw new Exception("Browser is not correct");
}
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
<...>
}
BaseTest class gets property & creates new instance of the Driver inside #BeforeClass method (browser name passed with a maven command when running the test):
String browserName = getParamater("browser");
driver = new Driver(browserName);
In the Test class inside the #Test I create new Actions & pass there the driver from BaseTest:
Actions builder = new Actions(driver);
Action mouseOverHome = builder
.moveToElement(pb.testGoodle)
.build();
mouseOverHome.perform();
And this code doesn’t work -> no Actions performed (no mouse over or anything), no errors too.
However if I create & define new WebDriver inside the #Test itself:
System.setProperty("webdriver.gecko.driver", "src/test/resources/geckodriver");
WebDriver driver = new FirefoxDriver();
Actions perfectly working.
Any ideas or hints very appreciated!
Resolved! Resolved! The problem was in messed Actions declaration in Page Object! Here how things look in the Page Object:
protected Driver driver;
public static Actions act;
public PlanBuilder(Driver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
this.act = new Actions(driver);
}
public void rightClick (WebElement element) throws InterruptedException {
// Actions builder = new Actions(basedriver);
Action openContextMenu = driver.act
.contextClick(element)
.build();
openContextMenu.perform();
Thread.sleep(4000);
}
public class BasePage
{
public static IWebDriver driver;
public static JObject jobject;
public static JArray jarray;
public static void SeleniumInit()
{
BasePage.ReadJsonObject("InitData.json");
string browser = jobject.SelectToken("browser").Value<string>();
string Headless = jobject.SelectToken("Headless").Value<string>();
if (browser == "Chrome")
{
ChromeOptions options = new ChromeOptions();
options.AddArguments("-start-maximized");
if (Headless == "True")
{
options.AddArguments("-headless");
}
driver = new ChromeDriver(options);
}
else if (browser == "Firefox")
{
FirefoxOptions options = new FirefoxOptions();
options.AddArguments("-start-maximized");
if (Headless == "True")
{
options.AddArguments("-headless");
}
driver = new FirefoxDriver(options);
}
else
{
EdgeOptions options = new EdgeOptions();
options.AddArguments("-start-maximized");
if (Headless == "True")
{
options.AddArguments("-headless");
}
driver = new EdgeDriver(options);
}
}
public static void Write(By by, string user)
{
try
{
driver.FindElement(by).SendKeys(user);
TakeScreenshot(Status.Pass, "Write " + user);
}
catch (Exception ex)
{
TakeScreenshot(Status.Fail, "Write Failed: " + ex.ToString());
Assert.Fail();
}
}
public static void Click(By by)
{
try
{
driver.FindElement(by).Click();
TakeScreenshot(Status.Pass, "Click");
}
catch (Exception ex)
{
TakeScreenshot(Status.Fail, "Click Failed: " + ex.ToString());
Assert.Fail();
}
}
public static void OpenUrl(string url)
{
try
{
driver.Url = url;
TakeScreenshot(Status.Pass, "Open url: " + url);
}
catch (Exception ex)
{
TakeScreenshot(Status.Fail, "Open Url Failed: " + ex.ToString());
Assert.Fail();
}
}
public static void Clear(By by)
{
try
{
driver.FindElement(by).Clear();
TakeScreenshot(Status.Pass, "Clear Text: " );
}
catch (Exception ex)
{
TakeScreenshot(Status.Fail, "Clear Text Failed: " + ex.ToString());
Assert.Fail();
}
}
public static void ClickRadio(By by)
{
try
{
Actions actions = new Actions(driver);
IWebElement radioLocator = driver.FindElement(by);
actions.Click(radioLocator).Build().Perform();
TakeScreenshot(Status.Pass, "Click Radio Button");
}
catch (Exception ex)
{
TakeScreenshot(Status.Fail, "Radio Button Click Failed: " + ex.ToString());
Assert.Fail();
}
}
public static void SelectOption(By by, string value)
{
try
{
var dropdown = driver.FindElement(by);
var selectDropdown = new SelectElement(dropdown);
selectDropdown.SelectByValue(value);
TakeScreenshot(Status.Pass, "Select Option from Dropdown Menu");
}
catch (Exception ex)
{
TakeScreenshot(Status.Fail, "Select Option Failed: " + ex.ToString());
Assert.Fail();
}
}
public static string GetElementText(By by)
{
string text;
try
{
text = driver.FindElement(by).Text;
}
catch
{
try
{
text = driver.FindElement(by).GetAttribute("value");
}
catch
{
text = driver.FindElement(by).GetAttribute("innerHTML");
}
}
return text;
}
public static void Assertion(By by, string assertText)
{
try {
string Text = GetElementText(by);
Assert.AreEqual(assertText, Text);
TakeScreenshot(Status.Pass, "Assertion Passed");
}
catch (Exception ex)
{
TakeScreenshot(Status.Fail, "Assertion Failed: " + ex.ToString());
Assert.Fail();
}
}
public static void sleep()
{
Thread.Sleep(10000);
}
public static string GetElementState(By by)
{
string elementState = driver.FindElement(by).GetAttribute("Disabled");
if (elementState == null)
{
elementState = "enabled";
}
else if (elementState == "true")
{
elementState = "disabled";
}
return elementState;
}
public static void ExplicitWait(By by)
{
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(60));
wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(by));
//wait.Until(Driver => IsPageReady(Driver) == true && IsElementVisible(by) == true && IsClickable(by) == true);
//wait.IgnoreExceptionTypes(typeof(NoSuchElementException));
//wait.Until(driver => IsElementVisible(driver, By.Id("username")) == true);
}
public static void ImplicitWait()
{
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(60);
}
public static void FluentWait()
{
DefaultWait<IWebDriver> fluentWait = new DefaultWait<IWebDriver>(driver);
fluentWait.Timeout = TimeSpan.FromSeconds(60);
fluentWait.PollingInterval = TimeSpan.FromMilliseconds(250);
/* Ignore the exception - NoSuchElementException that indicates that the element is not present */
fluentWait.IgnoreExceptionTypes(typeof(NoSuchElementException));
fluentWait.Message = "Element to be searched not found";
}
public static void scrollDown()
{
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("window.scrollTo(0, document." + "Body" + ".scrollHeight);");
}
public static void switchWindow()
{
driver.SwitchTo().Window(driver.WindowHandles[1]);
}
public static void TakeScreenshot(Status status, string stepDetail)
{
string path = #"C:\ExtentReports\" + "TestExecLog_" + DateTime.Now.ToString("yyyyMMddHHmmss");
Screenshot image = ((ITakesScreenshot)driver).GetScreenshot();
image.SaveAsFile(path + ".png", ScreenshotImageFormat.Png);
ExtentReport.exChildTest.Log(status, stepDetail, MediaEntityBuilder.CreateScreenCaptureFromPath(path + ".png").Build());
}
public static void ReadJson(string filename)
{
string myJsonString = File.ReadAllText(#"..\\..\\..\\" + filename);
jarray = JArray.Parse(myJsonString);
}
public static void ReadJsonObject(string filename)
{
string myJsonString = File.ReadAllText(#"..\\..\\..\\" + filename);
jobject = JObject.Parse(myJsonString);
}
}

Selenium Stale Element Reference Exception

Everytime got StaleElementReferenceException exception.
Here is a method, pls help.
private void selectAndClickRow(String elementName, boolean doubleClick) {
try {
String elementXpath = "//tr//td//div[contains(text(),'" + elementName + "')]";
new WebDriverWait(Init.getWebDriver(), Init.getTimeOutInSeconds()).until(ExpectedConditions.visibilityOf(Init.getDriverExtensions().waitUntilElementAppearsInDom(By.xpath(elementXpath))));
WebElement row = table.findElements(By.xpath(elementXpath)).get(0);
row.click();
if (doubleClick) {
row.click();
}
Init.getDriverExtensions().waitUntilElementAppearsInDom(By.xpath("//tr//td[contains(#class,'selected')]//div[contains(text(),'" + elementName + "')]"));
} catch (StaleElementReferenceException e) {
freeze(1);
selectAndClickRow(elementName, doubleClick);
}
waitToLoad();
}
public WebElement waitUntilElementAppearsInDom(By by) {
Wait wait = new WebDriverWait(Init.getWebDriver(), (long)Init.getTimeOutInSeconds());
wait.until(ExpectedConditions.presenceOfElementLocated(by));
return Init.getWebDriver().findElement(by);
}
I already added an element research and waiting for a second. It doesn't help.
I guess, you are trying to double click on a element. You can use actions class as given below instead of clicking twice on a element.
private void selectAndClickRow(String elementName, boolean doubleClick) {
try {
String elementXpath = "//tr//td//div[contains(text(),'" + elementName + "')]";
new WebDriverWait(Init.getWebDriver(), Init.getTimeOutInSeconds()).until(ExpectedConditions.visibilityOf(Init.getDriverExtensions().waitUntilElementAppearsInDom(By.xpath(elementXpath))));
WebElement row = table.findElements(By.xpath(elementXpath)).get(0);
new Actions(driver).doubleClick(row).perform();
} catch (StaleElementReferenceException e) {
//freeze(1);
//selectAndClickRow(elementName, doubleClick);
}
waitToLoad();
}

Wait for a page to fully load in Selenium

I am using selenium with Java. I want to wait for page to load fully before doing any action on that page.
I have tried the following method, but it is failing to work as expected.
public void waitForElementToBeVisible(final WebElement element) {
WebDriverWait wait = new WebDriverWait(WebDriverFactory.getWebDriver(), WEBDRIVER_PAUSE_TIME);
wait.until(ExpectedConditions.visibilityOf(element));
WebDriverWait inherits methods like wait until.
So something like
webDriverWait.until(ExpectedConditions.visibilityOfElementLocated( elementLocator)
should work. You can use ExpectedConditions, it would make things simpler. You can also use the method visibilityOfAllElements
This method will wait until element is visible.
Firstly this method will check, whether element is available in html and whether it's display.. it will wait until element will display..
public void E_WaitUntilElementDisplay() throws Exception
{
int i=1;
boolean eleche,eleche1 = false;
while(i<=1)
{
try{
eleche = driver.findElements(by.xpath("path")).size()!=0;
}catch(InvalidSelectorException ISExcep)
{
eleche = false;
}
if(eleche == true)
{
while(i<=1)
{
try{
eleche1=driver.findElement(By.xpath("Path")).isDisplayed();
}catch(org.openqa.selenium.NoSuchElementException NSEE){
eleche1=false;
}
if(eleche1 == true)
{
i=2;
System.out.println("\nElement Displayed.");
}
else
{
i=1;
Thread.sleep(1500);
System.out.println("\nWaiting for element, to display.");
}
}
}
else
{
i=1;
Thread.sleep(1500);
System.out.println("\nWaiting for element, to display.");
}
}
}
As another option maybe you can try something like:
if(element.isDisplayed() && element.isEnabled()){
//your code here
}
or if you know how long you want to wait:
thread.sleep(3000); //where 3000 is time expression in milliseconds, in this case 3 secs
You can use this function in java to verify whether the page is fully loaded or not. The verification happens two-fold. One using the javascript document.readystate and imposing a wait time on javascript.
/* Function to wait for the page to load. otherwise it will fail the test*/
public void waitForPageToLoad() {
ExpectedCondition<Boolean> javascriptDone = new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
try {
return ((JavascriptExecutor) getDriver()).executeScript("return document.readyState").equals("complete");
} catch (Exception e) {
return Boolean.FALSE;
}
}
};
WebDriverWait wait = new WebDriverWait(getDriver(), waitTimeOut);
wait.until(javascriptDone);
}
This works for me:
wait.until(ExpectedConditions.not(
ExpectedConditions.presenceOfElementLocated(
By.xpath("//div[contains(text(),'Loading...')]"))));
Here is the ultimate solution specifically when you are dealing with Angular 7 or 8.
Instead of waiting for a longer duration using sleep or implicit wait methods, you can divide your wait time into the partition and use it recursively.
Below logic will wait for the page to render for a minimum of 300 seconds and a maximum of 900 seconds.
/**
* This method will check page loading
*
*/
public void waitForLoadingToComplete() {
waitLoadingTime(3); // Enter the number of attempts you want to try
}
private void waitLoadingTime(int i) {
try {
// wait for the loader to appear after particular action/click/navigation
this.staticWait(300);
// check for the loader and wait till loader gets disappear
waitForElementToBeNotPresent(By.cssSelector("Loader Element CSS"));
} catch (org.openqa.selenium.TimeoutException e) {
if (i != 0)
waitLoadingTime(i - 1);
}
}
/**
* This method is for the static wait
*
* #param millis
*/
public void staticWait(final long millis) {
try {
TimeUnit.MILLISECONDS.sleep(millis);
} catch (final InterruptedException e) {
System.err.println("Error in staticWait." + e);
}
}
public void waitForElementToBeNotPresent(final By element) {
long s = System.currentTimeMillis();
new WebDriverWait(this.getDriver(), 30)
.until(ExpectedConditions.not(ExpectedConditions.presenceOfAllElementsLocatedBy(element)));
System.err.println("Waiting for Element to be not present completed. " + (System.currentTimeMillis() - s));
}

How to click on mail using selenium webdriver?

I want to open the mail by clicking on it, after receiving the activation mail.
For that I am using keyword driven framework.
So can anyone please let me know that how can we click on element without using List<>.
Because in my coding structure I am returning the object of Webelement instead of List<> object.
Note: Please suggest the solution without using JavaMail Api or if suggest please let me know according to the keyword driven framework.
Way of code structure where I find the elements in one method and in another method after getting an element perform the operations:
private boolean operateWebDriver(String operation, String Locator,
String value, String objectName) throws Exception {
boolean testCaseStep = false;
try {
System.out.println("Operation execution in progress");
WebElement temp = getElement(Locator, objectName);
System.out.println("Get Element ::"+temp);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//For performing click event on any of the button, radio button, drop-down etc.
if (operation.equalsIgnoreCase("Click")) {
temp.click();
}
/*Trying to click on subject line of "Email"*/
if (operation.equalsIgnoreCase("Click_anElement")) {
Thread.sleep(6000L);
Select select = new Select(temp);
List<WebElement> options= select.getOptions();
for(WebElement option:options){
System.out.println(option.getText());
}
/*try
{
if(temp.getText().equals(value)){
temp.click();
}
}
catch(Exception e){
System.out.println(e.getCause());
}*/
/*if (value != null) {
temp.click();
}*/
}
}
testCaseStep = true;
} catch (Exception e) {
System.out.println("Exception occurred operateWebDriver"
+ e.getMessage());
System.out.println("Taking Screen Shot");
TakesScreenshot ts=(TakesScreenshot)driver;
File source=ts.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(source, new File("./Screenshots/"+screenshotName+".png"));
System.out.println("Screenshot taken");
}
return testCaseStep;
}
public WebElement getElement(String locator, String objectName) throws Exception {
WebElement temp = null;
System.out.println("Locator-->" + locator);
if (locator.equalsIgnoreCase("id")) {
temp = driver.findElement(By.id(objectName));
} else if (locator.equalsIgnoreCase("xpath")) {
temp = driver.findElement(By.xpath(objectName));
System.out.println("xpath temp ----->" + temp);
} else if (locator.equalsIgnoreCase("name")) {
temp = driver.findElement(By.name(objectName));
}else if (locator.equalsIgnoreCase("cssSelector")) {
temp = driver.findElement(By.cssSelector(objectName));
}
return temp;
}

Make an existing code in Java parallel/multithread

I have a very simple crawler. I want to make my current code run in a few threads. Could you provide me a little tutorial or article to help me achive this test?
I'm originally a .Net developer and in .Net I have no problem whatsoever running codes in multithread but unfortunately I don't know anything about threads in Java.
My crawler is a command-line software so don't worry about GUI.
Thank you in advance.
Java does multithreading through the Thread class. One of the most common ways to make existing code multithreaded is to use the Runnable interface to define what you want to call at thread start, and then start it off.
public class SomeFunctions
{
public static void FunctionA() {}
public static void FunctionB() {}
public static void FunctionC() {}
}
// ...
Thread t1 = new Thread(new Runnable() {
public void run() {
SomeFunctions.FunctionA();
}
});
t1.start();
// (rinse and repeat for the other functions)
Dry coded, but it should at least get the general concept across. Of course, as soon as you go into multithreading land, you have concurrency issues and need to make sure everything is appropriately syhchronized, etc., but any language will have those issues.
If you're worried about synchronization, you have a few tools at your disposal. The easiest is the recursive mutex functionality built into Java, the "synchronized" keyword. More classical means are also available through various classes in the java.util.concurrent and java.util.concurrent.locks packages such as Semaphore and ReadWriteLock
http://download.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.html
http://download.oracle.com/javase/6/docs/api/java/util/concurrent/locks/package-summary.html
You can take a look at my webcrawler example. Sry for the lengthiness.
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* A web crawler with a Worker pool
*
* #author Adriaan
*/
public class WebCrawler implements Manager {
private Set<Worker> workers = new HashSet<Worker>();
private List<String> toCrawl = new ArrayList<String>();
private Set<String> crawled = new HashSet<String>();
private Set<String> hosts = new HashSet<String>();
private Set<String> results = new HashSet<String>();
private int maxResults;
public WebCrawler(String url, int numberOfWorkers, int maxResults) {
this.maxResults = maxResults;
toCrawl.add(url);
createWorkers(numberOfWorkers);
}
public void createWorkers(int numberOfWorkers) {
for (int i = 0; i < numberOfWorkers; i++) {
workers.add(new Worker(this));
}
}
private void stopWorkers() {
for (Worker worker : workers) {
worker.terminate();
}
}
public synchronized Job getNewJob() {
while (toCrawl.size() == 0) {
try {
wait();
} catch (InterruptedException e) {
// ignore
}
}
return new EmailAddressCrawlJob().setDescription(toCrawl.remove(0));
}
public synchronized void jobCompleted(Job job) {
// System.out.println("crawled: " + job.getDescription());
crawled.add(job.getDescription());
String host = getHost(job.getDescription());
boolean knownHost = hosts.contains(host);
if (!knownHost) {
System.out.println("host: " + host);
hosts.add(host);
}
for (String url : job.getNewDescriptions()) {
if (!crawled.contains(url)) {
if (knownHost) {
toCrawl.add(toCrawl.size() - 1, url);
} else {
toCrawl.add(url);
}
}
}
for (String result : job.getResults()) {
if (results.add(result)) {
System.out.println("result: " + result);
}
}
notifyAll();
if (results.size() >= maxResults) {
stopWorkers();
System.out.println("Crawled hosts:");
for (String crawledHost : hosts) {
System.out.println(crawledHost);
}
Set<String> uncrawledHosts = new HashSet<String>();
for (String toCrawlUrl : toCrawl) {
uncrawledHosts.add(getHost(toCrawlUrl));
}
System.out.println("Uncrawled hosts:");
for (String unCrawledHost : uncrawledHosts) {
System.out.println(unCrawledHost);
}
}
if (crawled.size() % 10 == 0) {
System.out.println("crawled=" + crawled.size() + " toCrawl="
+ toCrawl.size() + " results=" + results.size() + " hosts="
+ hosts.size() + " lastHost=" + host);
}
}
public String getHost(String host) {
int hostStart = host.indexOf("://") + 3;
if (hostStart > 0) {
int hostEnd = host.indexOf("/", hostStart);
if (hostEnd < 0) {
hostEnd = host.length();
}
host = host.substring(hostStart, hostEnd);
}
return host;
}
public static void main(String[] args) throws MalformedURLException {
new WebCrawler("http://www.nu.nl/", 5, 20);
}
}
Worker
**
* A Worker proactively gets a Job, executes it and notifies its manager that
* the Job is completed.
*
* #author Adriaan
*/
public class Worker extends Thread {
private final Manager manager;
private Job job = null;
private boolean isWorking;
public Worker(Manager manager) {
this.manager = manager;
isWorking = true;
start();
}
#Override
public void run() {
System.out.println("Worker " + Thread.currentThread().getId()
+ " starting ");
while (isWorking) {
job = manager.getNewJob();
job.execute();
manager.jobCompleted(job);
}
}
public void terminate() {
isWorking = false;
}
}
Manager interface
/**
* Manager interface for Workers
*
* #author Adriaan
*/
public interface Manager {
/**
* Gets a new job
*
* #return
*/
public Job getNewJob();
/**
* Indicates the job is completed
*
* #param job
*/
public void jobCompleted(Job job);
}
Job
import java.util.HashSet;
import java.util.Set;
/**
* A Job is a unit of work defined by a String (the description). During execution the
* job can obtain results and new job descriptions.
*
* #author Adriaan
*/
public abstract class Job {
private String description;
private Set<String> results = new HashSet<String>();
private Set<String> newDescriptions = new HashSet<String>();
/**
* Sets the job description
*
* #param description
* #return this for chaining
*/
public Job setDescription(String description) {
this.description = description;
return this;
}
/**
* Executes the job
*/
public abstract void execute();
/**
* Gets the results obtained
*
* #return
*/
public Set<String> getResults() {
return results;
}
/**
* Gets the now job descriptions obtained
*
* #return
*/
public Set<String> getNewDescriptions() {
return newDescriptions;
}
/**
* Gets the job description
*
* #return
*/
public String getDescription() {
return description;
}
/**
* Allows the implementation to add an obtained result
*
* #param result
*/
void addResult(String result) {
results.add(result);
}
/**
* Allows the implementation to add an obtained description
*
* #param result
*/
void addNewDescription(String newDescription) {
newDescriptions.add(newDescription);
}
}
A Job which crawls a page for email addresses:
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* A Job which crawls HTTP or HTTPS URL's for email adresses, collecting new
* URL's to crawl along the way.
*
* #author Adriaan
*/
public class EmailAddressCrawlJob extends Job {
#Override
public void execute() {
try {
URL url = new URL(getDescription());
if (url != null) {
String text = readText(url);
extractNewDescriptions(text, url);
extractResults(text);
}
} catch (MalformedURLException e) {
System.err.println("Bad url " + getDescription());
}
}
private String readText(URL url) {
URLConnection connection;
try {
connection = url.openConnection();
InputStream input = connection.getInputStream();
byte[] buffer = new byte[1000];
int num = input.read(buffer);
if (num > 0) {
StringBuilder builder = new StringBuilder();
builder.append(new String(buffer, 0, num));
while (num != -1) {
num = input.read(buffer);
if (num != -1) {
builder.append(new String(buffer, 0, num));
}
}
return builder.toString();
}
} catch (IOException e) {
//System.err.println("Could not read from " + url);
}
return "";
}
private void extractNewDescriptions(String text, URL url) {
// URL extracting code from Sun example
String lowerCaseContent = text.toLowerCase();
int index = 0;
while ((index = lowerCaseContent.indexOf("<a", index)) != -1) {
if ((index = lowerCaseContent.indexOf("href", index)) == -1) {
break;
}
if ((index = lowerCaseContent.indexOf("=", index)) == -1) {
break;
}
index++;
String remaining = text.substring(index);
StringTokenizer st = new StringTokenizer(remaining, "\t\n\r\">#");
String strLink = st.nextToken();
if (strLink.startsWith("javascript:")) {
continue;
}
URL urlLink;
try {
urlLink = new URL(url, strLink);
strLink = urlLink.toString();
} catch (MalformedURLException e) {
// System.err.println("Could not create url: " + target
// + " + " + strLink);
continue;
}
// only look at http links
String protocol = urlLink.getProtocol();
if (protocol.compareTo("http") != 0
&& protocol.compareTo("https") != 0) {
// System.err.println("Ignoring: " + protocol
// + " protocol in " + urlLink);
continue;
}
addNewDescription(urlLink.toString());
}
}
private void extractResults(String text) {
Pattern p = Pattern
.compile("([\\w\\-]([\\.\\w])+[\\w]+#([\\w\\-]+\\.)+[A-Za-z]{2,4})");
Matcher m = p.matcher(text);
while (m.find()) {
addResult(m.group(1));
}
}
}
I know this answer is a bit verbose, but I thought OP might be best helped with a working example and I happened to have made one not so long ago.
A very basic java program that will give the abstract idea of the Multi Threading..
public class MyThread extends Thread {
String word;
public MyThread(String rm){
word = rm;
}
public void run(){
try {
for(;;){
System.out.println(word);
Thread.sleep(1000);
}
} catch(InterruptedException e) {
System.out.println("sleep interrupted");
}
}
public static void main(String[] args) {
Thread t1=new MyThread("First Thread");
Thread t2=new MyThread("Second Thread");
t1.start();
t2.start();
}
}
And the Output will be..
First Thread
Second Thread
First Thread
Second Thread
First Thread
Go with this PPT it will help you with the basics..
Here

Categories