Selenium Notes
Selenium Notes
Assignements:
1. Checkboxes exercise
2. UI(Dropdowns,EditBoxes,Error Valdiation)
3. Synchronization with Explicit wait – Assignment
4. Window Handling
5. Frames
6. writing dynamic tests with out hardcoding values[After lec97]
FEATURES:
open Source
exclusively for Web Based applications.
multiple browsers
Multiple Platforms
multiple languages
Difference between Selenium and WebDriver?
Selenium WebDriver Architectue Simplified:
After you trigger the Test, complete Selenium code (Client) which we
have written will be converted to Json format
Generated Json is sent to Browser Driver (Server) through http Protocol.
Note: Each browser contains a separate browser driver
.Browser drivers communicate with its respective browser and executes
the commands by interpreting Json which It received on the browser.
Browser Driver receives responses back from the browser and it sends
Json response back to Client.
driver.findElement(By.xpath("//
input[@placeholder='Name']")).sendKeys("Aditya Gupta");
Css Selector-
EXAMPLE :
<input type="text" placeholder="Username” value=" ">
Xpath –
//Tagname[@attribute=’value’]
<input type="text" placeholder="Username" id=
“inputUsername” value=" ">
Therefore == >>> //input[@placeholder=’ Username’’]
driver.findElement(By.xpath("//button[text()='Log Out']")).click();
// driver.findElement(By.xpath("//*[text()='Log Out']")).click();
//line 68 be written as...
Handling Checkboxes
Handling radio buttons
Handling Text Buttons
Handling Alerts-Java Popups
Selenium Webdriver Form Methods
</select>
WebElement staticDropdown =
d.findElement(By.id("ctl00_mainContent_DropDownListCurrency"));
Dynamic Dropdown:
// a[@value='BLR'] --> appears 2 times dynamically(@origin and
@destination) once origin is selected
// Therefore==>(//a[@value='BLR'])[2] USED
d.findElement(By.xpath("(//a[@value='BLR'])[2]")).click();
the single forward slash (/) selects only the immediate child
elements, while the double forward slash (//) selects all
descendants of the current node, regardless of their level.
//System.out.println(option.getText());
if(option.getText().equalsIgnoreCase("India")) {
option.click();
break;
WebElement destination=driver.findElement(By.id("hp-widget__sTo"));
destination.clear();
destination.sendKeys("DEL");
Thread.sleep(2000);
destination.sendKeys(Keys.ARROW_DOWN);
destination.sendKeys(Keys.ENTER);
*/
Assert.assertFalse(d.findElement(By.cssSelector("input[id*='SeniorCitizenDi
scount']")).isSelected());
Assert.assertFalse(d.findElement(By.cssSelector("input[id*='SeniorCitizenDi
scount']")).isSelected());
Assert.assertEquals(d.findElement(By.id("divpaxinfo")).getText(), "5
Adult");
java.lang.AssertionError: expected [5 Adult] but found [4 Adult]
//Handling Calendar:
Many a time a test fails to click on an element or enter text in a field as
the element is
disabled or exists in the DOM, but is not displayed on the page; this will
result in an error
being thrown and the test resulting in failures. For building reliable
tests that can run
unattended, a robust exception and error handling is needed in the test
flow.
We can handle these problems by checking the state of elements. The
WebElement class
provides the following methods to check the state of an element:
Method Purpose
isEnabled() This method checks if an element is enabled. Returns true if
enabled,
else false for disabled.
isSelected() This method checks if element is selected (radio button,
checkbox, and
so on). It returns true if selected, else false for deselected
isDisplayed() This method checks if element is displayed.
In this recipe, we will use some of these methods to check the status and
handle
possible errors.
Locators for class type element:
<a class="ui-state-default ui-state-highlight ui-state-active"
href="#">7</a>
XPATH: //a[@class='ui-state-default ui-state-highlight ui-state-hover']
CSS: .ui-state-default.ui-state-highlight.ui-state-hover (Refer basics)
import java.io.File;
import java.io.IOException;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.os.WindowsUtils;
import org.apache.commons.io.FileUtils;
System.setProperty("webdriver.chrome.driver", "C://work//chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
WindowsUtils.killByName("excel.exe");
// driver.manage().deleteCookieNamed("sessionKey");
/* driver.get("http://google.com");
File src=
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src,new File("C:\\Users\\rahul\\screenshot.png"));*/
//Synchronizations in Selenium:
Implicit Wait in Selenium is used to tell the web driver to wait for a certain amount of time before it
throws a “No Such Element Exception”. ==> doesn't exist
Explicit Wait in Selenium is used to tell the Web Driver to wait for certain conditions (Expected
Conditions) or maximum time exceeded before throwing “ElementNotVisibleException” exists,
but it is hidden so the webDriver cannot find and interact with it. exception. It is an intelligent
kind of wait, but it can be applied only for specified elements.
Thread.Sleep: If results laoded in 3 seconds and thread.sleep(5000)…it will wait for 5 sec instead
og 3 sec…Therefore Implicit and explicit should be used….
Fluent wait: It will finds the web element reputedly at regular intervals of time until the timeout
or till the Object gets found, DISAV Code is Diff
Fluent wait is a class and an implementation of Wait interface and also parent class of
WebDriverWait.
Example:
Example:
</div>
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
System.setProperty("webdriver.chrome.driver","C:\\work\\chromedriver.exe");
// driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("https://alaskatrips.poweredbygps.com/g/pt/hotels?MDPCID=ALASKA-
US.TPS.BRAND.hotels.HOTEL");
driver.findElement(By.id("H-destination")).sendKeys("nyc");
driver.findElement(By.id("H-destination")).sendKeys(Keys.TAB);
driver.findElement(By.id("H-fromDate")).sendKeys(Keys.ENTER);
d.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@id='resultsContainer']/
section/article[1]")));
//Thread.sleep(5000L);
driver.findElement(By.xpath("//div[@id='resultsContainer']/section/
article[1]")).click();
}
DOUBT: FluentWaitTest: Scripting difference ???
keys.tab vs click() method in selenium
??AJAX/Mouse Interactions:
3. dragAndDrop(): Drags the element from one point and drops to another
Iterator is an object that can be used to loop through collections, like ArrayList and HashSet. It is called an "iterator" because
"iterating" is the technical term for looping. The iterator() method can be used to get an Iterator for
any collection:
import java.util.ArrayList;
import java.util.Iterator;
public class Main {
// Make a collection
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
Iterator<String> it = cars.iterator();
System.out.println(it.next());
Therefore its CSS .im-para.red or p.im-para.red and not like this p.im-para red [Tagname.class]/[.class]Under CSS
Frames:
a.dragAndDrop(source, target).build().perform();
a.dragAndDrop(source, target).build().perform();
What are Frames: its independent(has its own html) of html code, separate-container hosted on webpage, Selenium cant identify since
it’s a frame…
The Selenium WebDriver's Advanced User Interactions API allows us to perform operations from keyboard events and simple mouse events
to complex events such as dragging-and-dropping, holding a key and then performing mouse operations by using the Actions class, and
building a complex chain of events exactly like a user doing these manually. The Actions class implements the builder pattern to create a
composite action containing a group of other actions
We need to create an instance of the Actions class by passing the instance of driver class to the constructor in the following way:
You can find more examples from below link: LEC 87- Action class
https://techblog.polteq.com/en/perform-a-sequence-of-actions-with-selenium-webdriver/
HTML frames allow developers to present documents in multiple views, which may be independent
windows or subwindows. Multiple views offer developers a way to keep certain information visible,
while other views are scrolled or replaced. For example, within the same window, one frame might
display a static banner, the second a navigation menu, and the third the main document that can be
scrolled through or replaced by navigating in the second frame.4
//Another Xpath Locators Examples: footer elements Under Limiting WebDriver Scope
4.Click on each link in the col and check if the pages are opening
for(int i = 1 ; i < coldriver.findElements(By.tagName("a")).size() ; i++) {
Iterator<String> it = windows.iterator();