MainMenu

Home Java Overview Maven Tutorials

Saturday, 14 January 2017

Basic Selenium Accessing WebElements In Selenium

For Video : Click Here


Access Elements in Selenium :
WebDriver driver = new ChromeDriver();
WebDriver is an interface and all the methods which are declared in WebDriver interface are implemented by respective driver class.

We generally do it this way because usually we want to be able to run our tests on multiple browsers. If we declare the driver as a specific driver type, we are then anchored to only that driver. This is not a problem if you only ever need to test on say Chrome for example. But what if you later want your tests to also be able to work with IE, Opera, Firefox, etc.?
These are extended classes of the WebDriver interface.
If your main tests and other classes define the commonly shared driver as simply WebDriver instead of specifically being tied to ChromeDriver, then the same tests can be run without change to the test code itself simply by initializing the shared driver object with a different driver extended class.

Let’s see why can’t we use the following statement.

WebDriver driver = new WebDriver();
We cannot write our code like this because we cannot create Object of an Interface.
WebDriver is an interface.

---------------------------------------------
WebDriver driver = new ChromeDriver();
We can create Object of a class FirefoxDriver by taking reference of an interface (WebDriver). In this case, we can call implemented methods of WebDriver interface.

WebDriver driver = new FirefoxDriver();


By this above line of code a default firefox browser will be launched means we have Initiated a FirefoxDriver class with no parameter. obj is the name of object, you can give any name of object as per your convenience.
----------------------------------------------------------------------------------------------------------

driver.get("URL")
driver.navigate().to("URL")
get() method will launch a new browser session and directs to the given URL.
Note : for single page application, navigate().to() will not refresh the page but get() will do also with navigate().back() we can navigate to the previous page.
-----------------------------------------------------------------------------------------------------------

driver.close()
close() method is used to close the browser or page currently which is having the focus..
----------------------------------------------------------------------------------------------------------

driver.dispose()
dispose() method is used to close all browser windows and safely end the sessions.
----------------------------------------------------------------------------------------------------------

driver.quit()
quit() method is used to shut down the web driver instance and close the all the browsers opened by selenium.
----------------------------------------------------------------------------------------------------------

findElement(By.locator())
This method is used to find the Elements in GUI.
There are different kinds of locator() :
By.className : this will find the value based on class Name
By.cssSelector : this will find the value based on cssSelector
By.id : this will find the value based on id attribute
By.linkText : this will find the link element by the exact text
By.partialLinkText : this will locate elements by the given link text
By.name : this will find the value based on name attribute
By.tagName : this will find the value based on tagname
By.xpath : It will locate elements via xpath
Note : xpath is an addon on firefox through which xpath can be received.
---------------------------------------------------------------------------------------------------------
WebElement.senKeys("text") : This is used to send data or text inside a box.
WebElement.clear() : This is used to clear data in input box.
WebElement.click() : This is used to click on link.
---------------------------------------------------------------------------------------------------------

How to create xpath?

xpath can be created manually also :
syntax : //tagname[@attributname='value of attribute']
for Text : //td[text()='name of text']
or for input Text box : //input[text()='name of text']
or //input[@id = "text"]
for link : //a[@href = 'http://www.way2testing.com']

xpath contains : //*[contains(@id, 'value')]
xpath following :Xpath = //*[@type='text']//following::input
xpath starts-with : .//*[starts-with(@id, 'value')]
-------------------------------------------------------------------------------------------------

Code to press ENTER in selenium


WebDriver driver = new FirefoxDriver();
Actions act = new Actions(driver);
act.sendKeys(Keys.ENTER).build().perform();
----------------------------------------------------------------------------------------------

Different Kind of waits in selenium


In Selenium There is different kind of Waits :
1). Thread.sleep(2000L); //wait for 2 seconds

2.)Page Load :

It will set the amount of time to wait for a page load to complete before throwing an error.
obj.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);

3). Implicit Wait : Implicit wait timeout once set, is set for the lifetime of the Webdriver Object Instance.
obj.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
This will wait upto 10 seconds, if elements is find before 10 second then it will move to next step.

4).Explicit Wait : 1.Explicit wait will make your code to wait for vertain condition to occur before moving forward.
2.This can be acieved with combination of WebDriverWait and ExpectedConditions.
3.WebDriverWait by default calls ExpectedCondition to poll by every 500 milliseconds until it return successfully.
WebDriverWait objwait = new WebDriverWait(obj, 10); // this will wait for 10 seconds
objwait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(""));

Example of Explicit Wait(Commond)


1). First Locate WebElement.
2). Create WebDriverWait object and pass reference of WebDriver & Time.
3). Implement conditions.

WebElement obj = driver.findElement(By.cssSelector(".innerWrap>:nth-child(1)>:nth-child(2)"));
WebDriverWait objwait = new WebDriverWait(driver, 10);
objwait.until(ExpectedConditions.visibilityOf(obj));

Implicit Wait : If wait is set, it will wait for specified amount of time for each findElement/findElements call. It will throw an exception if action is not complete. Explicit Wait : If wait is set, it will wait and move on to next step when the provided condition becomes true else it will throw an exception after waiting for specified time. Explicit wait is applicable only once wherever specified.


Example of Fluent Wait(Commond)


0). Fluent Wait commands are most useful when interacting with web elements that can sometimes take more time than usual to load. This is largely something that occurs in Ajax applications.
1).Fluent wait is just a plain class and using this class we can wait untill specific conditions are met.
Fluent wait is a class and is part of org.openqa.selenium.support.ui Package
It is an implementation of wait Interface.
2).In fluent wait, we can change the default polling period beased on our requirement.
Note :- By default , implicit wait, explicit wait , default polling time is 250 mili second.
3). Each Fluent wait instance defines, the maximum amount of time to wait for a condition and we can give the frequency with which to check the condition.
4). We can also ignore any exception while polling element such as ElementNotVisibleException, NoSuchElementException in selenium. Syntax :-
Wait wait = new FluentWait(driver)
.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(1, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
WebElement element = wait.until(new Function()
{
public WebElement apply(WebDriver driver)
{
return driver.findElement(By.xpath("");
}
}
);

----------------------------------------------------------------------------------------------

Code to Select Dropbox

Import the package "Select"
Select obj_name = new Select(driver.findElement(By.locator()));
obj_name.selectByVisibleText("text"); OR obj_name.selectByValue(); OR obj_name.selectByIndex();
For deselect : obj_name.deselectAll();
-----------------------------------------------------------------------------------------------
Right click on any WebElement
WebDriver driver = new ChromeDriver();
WebElement element = driver.findElement(By.xpath(""));
Actions action = new Actions(driver);
action.contextClick(element ).build().perform();

OR

Actions action= new Actions(driver);
action.contextClick(productLink).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.RETURN).build().perform();
-----------------------------------------------------------------------------------------------

Code for Mouse hover in selenium

Import the Actions and Action class
WebDriver driver = new FirefoxDriver();
Actions act = new Actions(driver);
WebElement element = driver.findElement(By.locatior());
Action obj4 = obj2.moveToElement(element).build();
obj4.perform();
OR
WebElement webele = webdriver.findElement(By.xpath("//html/body/div[13]/ul/li[4]/a"));
Actions action = new Actions(webdriver);
action.moveToElement(webele).build().perform();

OR
//Main Menu
WebElement mainMenu = driver.findElement(By.linkText("main_menu_link"));
//Create object 'action' of an Actions class
Actions actions = new Actions(driver);
//To mouseover on main menu
actions.moveToElement(mainMenu) ;

//Sub Menu
WebElement subMenu = driver.findElement(By.linkText("sub_menu_link"));
//To mouseover on sub menu
actions.moveToElement(subMenu);
//build() method is used to compile all the actions into a single step
actions.click().build().perform();
-----------------------------------------------------------------------------------------------

Code to perform Drag and Drop in selenium

Import the Actions class
WebDriver driver = new FirefoxDriver();
Actions action = new Actions(driver);
WebElement drag = driver.findElement(By.locatior());
WebElement drop = driver.findElement(By.locatior());
action.dragAndDrop(drag, drop).build().perform();
OR
//To get source locator
WebElement sourceLocator = driver.findElement(By.xpath("xpath"));
//To get target locator
WebElement targetLocator = driver.findElement(By.xpath("xpath"));
//create object 'action' of Actions class
Actions action = new Actions(driver);
//use dragAndDrop() method. It accepts two parametes source and target.
action.dragAndDrop(sourceLocator, targetLocator).build().perform();
-----------------------------------------------------------------------------------------------
How to get Entered Text from textbox

WebElement tb = driver.findElement(By.xpath(""));
String Enteredtext = tb.getAttribute("value");
and in case there is select box then
Select slt = new Select(driver.findElement(by.xpath("")));
selectItem.getFirstSelectedOption().getText();
-----------------------------------------------------------------------------------------------
Alert Handling in Selenium

Handling alerts manually is a tedious task. To reduce human intervention and ease this task, Selenium provides a wide range of functionalities and methods to handle alerts.
The following methods are useful to handle alerts in selenium:
1. Void dismiss(): This method is used when the ‘Cancel’ button is clicked in the alert box.
driver.switchTo().alert().dismiss();

2. Void accept(): This method is used to click on the ‘OK’ button of the alert.
driver.switchTo().alert().accept();

3. String getText(): This method is used to capture the alert message.
driver.switchTo().alert().getText();

4. Void sendKeys(String stringToSend): This method is used to send data to the alert box.
driver.switchTo().alert().sendKeys("Text");

-----------------------------------------------------------------------------------------------
Important Points in Selenium :

How to press enter key in selenium?


driver.findElement(By.id("Value")).sendKeys(Keys.ENTER);

How to press enter key "ctrl" & "t" or "tab" in selenium?


Robot robot = new Robot();
robot.keyPress(keyEvent.VK_CONTROL);
robot.keyPress(keyEvent.VK_T);
robot.keyRelease(KeyEvent.VK_T);
robot.keyRelease(KeyEvent.VK_CONTROL);

how to click on mouse using Robot class



robot.mouseMove(0, 900);

robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); //associated with mouse left click
robot.mousePress(InputEvent.BUTTON2_DOWN_MASK); //associated with mouse middle click
robot.mousePress(InputEvent.BUTTON3_DOWN_MASK); //associated with mouse right click

robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); //associated with mouse left click
robot.mouseRelease(InputEvent.BUTTON2_DOWN_MASK); //associated with mouse middle click
robot.mouseRelease(InputEvent.BUTTON3_DOWN_MASK); //associated with mouse right click

How to press enter key "ctrl" & "a" in selenium?

driver.findElement(By.cssSelector("body")).sendKeys(Keys.chord(Keys.CONTROL, "a"));

How to scroll in selenium?


Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_PAGE_DOWN);
robot.keyRelease(KeyEvent.VK_PAGE_DOWN);

There is also scroll method(horizontal, vertical) i.e. scroll(10, 200)
((JavascriptExecutor)drive).executeScript("scroll(10,300)");

((JavascriptExecutor)drive).executeScript("window.scrollBy(10,300)");

((JavascriptExecutor)drive).executeScript("window.scrollTo(0, document.body.scrollHeight)");

Scroll up to an element WebElement element = driver.findElement(By.xpath(""));
((JavascriptExecutor)drive).executeScript("arguments[0].scrollIntoView();" element);

OR

JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.scrollBy(0,250)", "");

How to handel alert & popup
Alert alert = driver.scitchTo().alert();
alert.accept();

driver.switchTo().ActiveElement();

driver.getWindowHandler();

Tags :-

How to open browser in selenium?

,

How to press Enter Key in selenium?

,

Different kinds of Waits in selenium

,

Explicit wait in selenium with example

,

How to select the value from Dropbox

,

How to perform mouse hover in selenium

,

how to press control + t in selenium

How to scroll in selenium

,

How to perform drag and drop action in selenium.

.

1 comment: