0% found this document useful (0 votes)
34 views

Selenium

Uploaded by

Pavan Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Selenium

Uploaded by

Pavan Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Frameworks:

https://www.edureka.co/blog/selenium-framework-data-keyword-hybrid-frameworks

Selenium:

->Download the Selenium java client and unzip it

->Open Eclipse and add new project – Go to configure build path and add external libs

Element locators:

->Open Firefox and download fire bug,firepath (deprecated in 2017)

-> In Chrome – right click – inspect elements – console -ctl+ F for searching dom- spy on the elements –
copy the Xpath, css selector
Selenium WebDriver defines two methods for identifying the elements, they
are findElement and findElements .
 findElement: This command is used to uniquely identify a web element within the web page.
 findElements: This command is used to uniquely identify the list of web elements within the web page.

 Difference between driver.close() & driver.quit()

close – It closes the browser window on which the focus is set.


driver. quit – It basically calls driver.dispose method which in turn closes all the browser windows and ends the
WebDriver session gracefull.


Chrome- Inspect

 The implicit wait will tell to the web driver to wait for certain amount of time before it throws a "No Such
Element Exception".

The explicit wait is used to tell the Web Driver to wait for certain conditions (Expected Conditions) or the
maximum time exceeded before throwing an "ElementNotVisibleException" exception.

 The fluent wait is used to tell the web driver to wait for a condition, as well as the frequency with which we
want to check the condition before throwing an "ElementNotVisibleException" exception.
import com.google.common.base.Function;

public class LocatorsConcept {

public static void main(String[] args) {


System.setProperty("webdriver.chrome.driver", "C:\\Users\\AC37118\\Downloads\\
chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS );
driver.get("https://login.yahoo.com/");

//1. ID : according to W3C standards the same ID will be unique


// driver.findElement(By.id("login-username")).sendKeys("[email protected]");
// driver.findElement(By.id("login-signin")).click();

//2. name
// driver.findElement(By.name("username")).sendKeys("[email protected]");
// driver.findElement(By.name("signin"));

//3.Xpath
// driver.findElement(By.xpath("//input[@id='login-username']")).sendKeys("[email protected]");
// driver.findElement(By.xpath("//input[@id='login-signin']")).click();

//4.cssSelector
// driver.findElement(By.cssSelector("#login-username")).sendKeys("[email protected]");
// driver.findElement(By.cssSelector("#login-signin")).click();

//5.linkText
// driver.findElement(By.linkText("Forgot username?")).click();
//

//6.partiallink text only for links but not recommended


//driver.findElement(By.partialLinkText("Forgot")).click();

//7.Classname: it is not unique


WebElement username= driver.findElement(By.className("phone-no"));

//Explicit wait:
WebDriverWait explicitwait= new WebDriverWait(driver,20);

explicitwait.until(ExpectedConditions.visibilityOf(username)).click();

//Fluentwait:
Wait<WebDriver> fluentwait= new FluentWait<WebDriver> (driver)
.withTimeout(10, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
WebElement clickseleniumlink = fluentwait.until(new Function<WebDriver, WebElement>(){
public WebElement apply(WebDriver driver ) {
return username;
}
});

driver.findElement(By.className("orko-button-primary orko-button challenge-button")).click();

driver.close();

//Tag name :

Select All options in a dropdown:

List<WebElement> liOp = new


Select(driver.findElement(By.id("YourLocator"))).getOptions();
for(WebElement eachElem:liOp){
new
Select(driver.findElement(By.id("yourLocator"))).selectByVisibleText(eachElem.getText());
}

Select dropdown=new Select(element);

dropdown.selectByIndex(1);

// Or can be used as

dropdown.selectByVisibleText("text");

// Or can be used as

dropdown.selectByValue("3");

List <WebElement> listopt=dropdown.getOptions();

for(WebElement eachelement: listopt) {

String eletext=eachelement.getText();

System.out.println(eletext);

Challenges in Selenium:
 it’s a free tool, so no direct support with our questions

1. Image or text overlapping issue: Ans – selenium is not smart to automate text/image overlapping
2. Can not support for captcha automation
3. Doestn’t support any we based applications
4. When you compare with QTP, silktest – for selenium we need proper oops concept and coding
5. No reporting supporting selenium (third party tool), but in QTP they supports reporting
6. Need to learn any programming language (Java…), to design complete framework.
7. Difficult to identify dynamic objects – in QTP object spy is there it will create it’s own xpath to identify.
But in selenium we must know about different locators.
8. Working with frames – switching between frames – multiple frames in a single page
9. Play back is very slow – IDE
10. Flash objects like youtube(you can not automate), applets….
11. Timeout resulting : biggest challenge like when to use implicit wait, explicit wait.
Wait’s won’t work some times then we need to java script executor- getting element exceptions
We should never use thread.sleep – if componenet is coming 10 sec and we put thread sleep for 5 sec it
fails. Thread.sleep will applicable for all the lines of code.
 Selenium is very slow with IE browser

Overview of WebDriver API Doc and sourcecode:


https://github.com/SeleniumHQ/selenium/blob/master/java/client/src/org/openqa/
selenium/WebDriver.java

https://www.selenium.dev/documentation/en/webdriver/
Handling frames:

Frame is a HTML doc(kind of element which is having no of elements) with in another HTML doc
To check frame click on the element – right click on just to above contacts-this frame.

Handling dynamic web table :


Chrome- Inspect elements – Ctrl+F
Selenium Webdriver- Architecture:

All the calls happening are REST api call from client to server – Get/POST
Driver.getwindowhandles() – Get RESP API call

https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol

Practice this calls in Postman

Explicit Wait in Selenium


By using the Explicit Wait command, the WebDriver is directed to wait until a certain
condition occurs before proceeding with executing the code.
Setting Explicit Wait is important in cases where there are certain elements that
naturally take more time to load. If one sets an implicit wait command, then the browser
will wait for the same time frame before loading every web element. This causes an
unnecessary delay in executing the test script.
Explicit wait is more intelligent, but can only be applied for specified elements. However,
it is an improvement on implicit wait since it allows the program to pause for dynamically
loaded Ajax elements.
In order to declare explicit wait, one has to use “ExpectedConditions”. The following
Expected Conditions can be used in Explicit Wait.
 alertIsPresent()
 elementSelectionStateToBe()
 elementToBeClickable()
 elementToBeSelected()
 frameToBeAvaliableAndSwitchToIt()
 invisibilityOfTheElementLocated()
 invisibilityOfElementWithText()
 presenceOfAllElementsLocatedBy()
 presenceOfElementLocated()
 textToBePresentInElement()
 textToBePresentInElementLocated()
 texttoBePresentInElementValue()
 titleIs()
 titleContains()
 visibilityOf()
 visibilityOfAllElements()
 visibilityOfAllElementsLocatedBy()
 visibilityOfElementLocated()
To use Explicit Wait in test scripts, import the following packages into the script.
import org.openqa.selenium.support.ui.ExpectedConditions

import org.openqa.selenium.support.ui.WebDriverWait

Then, Initialize A Wait Object using WebDriverWait Class.


WebDriverWait wait = new WebDriverWait(driver,30);

FLUENT WAIT

Wait wait = new FluentWait(WebDriver reference)

.withTimeout(timeout, SECONDS)

.pollingEvery(timeout, SECONDS)

.ignoring(Exception.class);
WebElement foo=wait.until(new Function<WebDriver, WebElement>() {

public WebElement applyy(WebDriver driver) {

return driver.findElement(By.id("foo"));

If you want to perform only one action, you can use either perform() or build().perform(), with the same
effect. But if you want to perform several actions, you have to use build().perform().

Actions a = new Actions(driver );

Example of one action with build().perform() -> OK:

a.moveToElement(someelement).build().perform();

Same example with only perform() -> OK

a.moveToElement(someelement).perform();

Example with several actions ( Has to be build().perform() ):

a.moveToElement(someelement).click().build().perform();

document : https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/
interactions/Actions.html

Alert:

WebElement element =driver.findElement(By.id(""));

Alert a=driver.switchTo().alert();

a.accept();

a.dismiss();

a.getText();

Actions act=new Actions(driver);

act.moveToElement(element).perform();//Shifts the mouse pointer to the


center of the element

act.contextClick(element);//Performs right-click on the mouse

act.doubleClick(element).perform(); //Performs double click on the element


act.clickAndHold(element);// Performs long click on

act.dragAndDrop(element, element);// Drags the element from one point and


drops to another

package com.crm.qa.testcases;

import java.io.File;

import java.util.Iterator;

import java.util.List;

import java.util.NoSuchElementException;

import java.util.Set;

import java.util.concurrent.TimeUnit;

import java.util.function.Function;

import org.openqa.selenium.Alert;

import org.openqa.selenium.By;

import org.openqa.selenium.TakesScreenshot;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebDriver.Navigation;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.interactions.Actions;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.FluentWait;

import org.openqa.selenium.support.ui.Select;

import org.openqa.selenium.support.ui.Wait;

import org.openqa.selenium.support.ui.WebDriverWait;

import org.testng.annotations.BeforeMethod;
import com.crm.qa.base.TestBase;

import com.crm.qa.pages.LoginPage;

import com.mongodb.MapReduceCommand.OutputType;

public class actionclass extends TestBase{

private static final TimeUnit SECONDS = null;

@BeforeMethod

public void setUp() {

initialization();

WebElement element =driver.findElement(By.id(""));

Alert a=driver.switchTo().alert(); //•NoAlertPresentException

a.accept();

a.dismiss();

a.getText();

Actions act=new Actions(driver);

act.moveToElement(element).perform();//Shifts the mouse pointer to the


center of the element

act.contextClick(element);//Performs right-click on the mouse

act.doubleClick(element).perform(); //Performs double click on the element

act.clickAndHold(element);// Performs long click on

act.dragAndDrop(element, element);// Drags the element from one point and


drops to another
Select dropdown=new Select(element);

dropdown.selectByIndex(1);

// Or can be used as

dropdown.selectByVisibleText("text");

// Or can be used as

dropdown.selectByValue("3");

List <WebElement> listopt=dropdown.getOptions();

for(WebElement eachelement: listopt) {

String eletext=eachelement.getText();

System.out.println(eletext);

String parent= driver.getWindowHandles().toString();

WebDriverWait wait =new WebDriverWait(driver, 30);

wait.until(ExpectedConditions.visibilityOf(element));

////https://www.browserstack.com/guide/expectedconditions-in-selenium

//The above code instructs Selenium WebDriver to wait for 30 seconds before
throwing a TimeoutException. If it finds the element before 30 seconds, then it will return immediately.

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

Wait<WebDriver> wait1 = new FluentWait<WebDriver>(driver)

.withTimeout(30, SECONDS)

.pollingEvery(5, SECONDS)
.ignoring(NoSuchElementException.class);

WebElement foo = wait1.until(new Function<WebDriver,


WebElement>() {

public WebElement apply(WebDriver driver) {

return driver.findElement(By.id("foo"));

});

driver.navigate().back();

driver.navigate().forward();

driver.navigate().refresh();

driver.navigate().to("");

driver.findElement(By.id("")).isEnabled();

driver.findElement(By.id("")).isDisplayed();

driver.findElement(By.id("")).isSelected();

// File f= ((TakesScreenshot)driver).getScreenshotAs(OutputType.File);

//

// //Convert web driver object to TakeScreenshot

//

// TakesScreenshot scrShot =((TakesScreenshot)driver);

//

// //Call getScreenshotAs method to create image file

//

// File SrcFile=scrShot.getScreenshotAs(OutputType.FILE);
//

//

// Load the website

driver.get("http://www.naukri.com/");

// It will return the parent window name as a String

String parent1=driver.getWindowHandle();

Set<String>s=driver.getWindowHandles();

// Now iterate using Iterator

Iterator<String> I1= s.iterator();

while(I1.hasNext())

String child_window=I1.next();

if(!parent1.equals(child_window))

driver.switchTo().window(child_window);

System.out.println(driver.switchTo().window(child_window).getTitle());

driver.close();
}

driver.switchTo().window(parent);

============================================== ============================

Locators :

//1. ID : according to W3C standards the same ID will be unique

// driver.findElement(By.id("login-username")).sendKeys("[email protected]");

// driver.findElement(By.id("login-signin")).click();

//2. name

// driver.findElement(By.name("username")).sendKeys("[email protected]");

// driver.findElement(By.name("signin"));

//3.Xpath

// driver.findElement(By.xpath("//input[@id='login-
username']")).sendKeys("[email protected]");

// driver.findElement(By.xpath("//input[@id='login-signin']")).click();
//4.cssSelector

// driver.findElement(By.cssSelector("#login-username")).sendKeys("[email protected]");

// driver.findElement(By.cssSelector("#login-signin")).click();

//5.linkText

// driver.findElement(By.linkText("Forgot username?")).click();

//

//6.partiallink text only for links but not recommended

//driver.findElement(By.partialLinkText("Forgot")).click();

//7.Classname: it is not unique

WebElement username= driver.findElement(By.className("phone-no"));

//Explicit wait:

WebDriverWait explicitwait= new WebDriverWait(driver,20);

explicitwait.until(ExpectedConditions.visibilityOf(username)).click();

You might also like