Professional Documents
Culture Documents
@@selenium QA
@@selenium QA
@@selenium QA
It does not support to test It does not support to test It support to test
iphone/Android iphone/Android iphone/Android
applications applications applications
Quit()-
Maximize- driver.manage().window().maximize();
Minimize – driver.manage().window().minimize();
Ans – SearchContext.
Ans-It is a interface.
All operations to do with intraction with a page will be performed through webElement
interface.
Methods of WebElement-
1) Clear Command
clear( ) : void – If this element is a text entry element, this will clear the value. This method
accepts nothing as a parameter and returns nothing.
Command – element.clear();
This method has no effect on other elements. Text entry elements are INPUT and
TEXTAREA elements.
2) SendKeys Command
This method works fine with text entry elements like INPUT and TEXTAREA elements.
3) Click Command
click( ) : void – This simulates the clicking of any element. Accepts nothing as a parameter
and returns nothing.
Command – element.click();
Clicking is perhaps the most common way of interacting with web elements like text
elements, links, radio boxes and many more.
4) IsDisplayed Command
Command – element.isDisplayed();
5) IsEnabled Command
isEnabled( ) : boolean – This determines if the element currently is Enabled or not? This
accepts nothing as a parameter but returns boolean value(true/false).
Command – element.isEnabled();
This will generally return true for everything but I am sure you must have noticed many
disabled input elements in the web pages.
6) IsSelected Command
isSelected( ) : boolean – Determine whether or not this element is selected or not. This
accepts nothing as a parameter but returns boolean value(true/false).
Command – element.isSelected();
This operation only applies to input elements such as Checkboxes, Select Options and Radio
Buttons. This returns True if the element is currently selected or checked, false otherwise.
7) Submit Command
submit( ) : void– This method works well/better than the click() if the current element is a
form, or an element within a form. This accepts nothing as a parameter and returns nothing.
Command – element.submit();
If this causes the current page to change, then this method will wait until the new page is
loaded.
8) getTagName Command
getTagName( ) : String– This method gets the tag name of this element. This accepts
nothing as a parameter and returns a String value.
Command – element.getTagName();
This does not return the value of the name attribute but return the tag for e.g. “input“ for the
element <input name="foo"/>.
9) getCssValue Command
getCssvalue( ) : String– This method Fetch CSS property value of the give element. This
accepts nothing as a parameter and returns a String value.
Command – element.getCssValue();
Color values should be returned as rgba strings, so, for example if the “background-color”
property is set as “green” in the HTML source, the returned value will be “rgba(0, 255, 0,
1)”.
getAttribute(String Name) : String– This method gets the value of the given attribute of the
element. This accepts the String as a parameter and returns a String value.
Command – element.getAttribute();
Attributes are Ids, Name, Class extra and using this method you can get the value of the
attributes of any given element.
getSize( ) : Dimension – This method fetch the width and height of the rendered
element. This accepts nothing as a parameter but returns the Dimension object.
Command – element.getSize();
getLocation( ) : Point – This method locate the location of the element on the page. This
accepts nothing as a parameter but returns the Point object.
Command – element.getLocation();
This returns the Point object, from which we can get X and Y coordinates of specific
element.
11) How many locator is avilable in webdriver & which locator is prefered?
Ans : ID Name,LinkText,Partial link Text,Tag Name,css class,css selector,xpath.Finding
elements by ID is usually going to be the fastest option, because at its root, it eventually
calls down to document.getElementById(), which is optimized by many browsers.
Ex:
Screen s=new Screen();
Example-
@Test
Public void getSize() throws Exception {
//Locate element for which you wants to get height and width.
WebElement Image = driver.findElement(By.xpath("//img[@border='0']"));
Unconditional Synchronization
In this case, only the timeout value to be specified. The tool will wait till certain
time before proceeding.
Examples: Wait(), Thread.Sleep()
The main advantage of this method is that it will come for help when we interact
with a third party system such as an interface. Here, it is not possible to write
condition or check for a condition. In such cases, the application can be made to
wait for a specific period using this type of synchronization. The major disadvantage
is that at some times, the tool will be made to wait unnecessarily even when the
application is ready.
Conditional Synchronization
In this case, a condition also will be specified along with the timeout value. The tool
will wait to check the condition and will come out if nothing happens. However, it is
important to set a timeout value also in conditional synchronization so that the tool
will proceed even if the condition is not met.
There three different types of conditional statements in selenium webdriver and
they are an implicit wait and explicit wait and fluent wait.
Implicit Wait
This can be used while trying to find out an element or elements and when they are
not readily available. The implicit wait will tell the webdriver to poll the DOM for a
certain period of time. However, this will not work for all commands but only for
“Find Element” and “Find Elements” statements.
Syntax
driver.manage.TimeOuts.implicitwait(6,Timeunit.SECONDS);
Example for Implicit Wait
WebDriver driver = new FirefoxDiriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get(“http://www.google.com”);
Explicit Wait
Here, in this case, a wait statement for certain conditions will be defined which
should be satisfied within the specified timeout period. The code will be executed if
the element is found within the specified time.
Example for Explicit Wait
/*Explicit wait for state dropdown field*/
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(“statedropdown”)))
;
Fluent Wait
This is used to define maximum amount of time to wait for a condition and also to
increase the frequency with which the conditions are checked. Using this type
certain types of exceptions such as “NoSuchElementExceptions” can be ignored
too.
Syntax
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
//Wait for the condition
.withTimeout(30, TimeUnit.SECONDS)
// which to check for the condition with interval of 5 seconds.
.pollingEvery(5, TimeUnit.SECONDS)
//Which will ignore the NoSuchElementException
.ignoring(NoSuchElementException.class);
Q.23. How to handle synchronization wait available in webdriver?
We need Expected conditions in Explicit wait to handle synchronization wait.
Explicit Wait-
Here, in this case, a wait statement for certain conditions will be defined which
should be satisfied within the specified timeout period. The code will be executed if
the element is found within the specified time.
Example for Explicit Wait
/*Explicit wait for state dropdown field*/
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(“statedropdown”)))
;
Expected conditions methods-
1.isElementPresent:
Syntax-
WebDriverWaitwait = new WebDriverWait(driver, waitTime);
wait.until(ExpectedConditions.presenceOfElementLocated(locator));
2.isElementClickable-
Syntax-
WebDriverWaitwait = new WebDriverWait(driver, waitTime);
wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
3.isElementVisible-
Syntax-
WebDriverWaitwait = new WebDriverWait(driver, waitTime);
wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
4.isElementInVisible-
Syntax-
WebDriverWaitwait = new WebDriverWait(driver, waitTime);
wait.until(ExpectedConditions.invisibilityOfElementLocated(locator));
5.isElementEnabled-
WebElement element = driver.findElement(By.id(""));
element.isEnabled();
6.isElementDisplayed-
WebElement element = driver.findElement(By.id(""));
element.isDisplayed();
7.Wait for invisibility of element-
WebDriverWaitwait = new WebDriverWait(driver, waitTime);
wait.until(ExpectedConditions.invisibilityOfElementWithText(by));
8.Wait for invisibility of element with Text-
WebDriverWaitwait = new WebDriverWait(driver, waitTime);
wait.until(ExpectedConditions.invisibilityOfElementWithText(by, strText));
Q.24. Which wait statement will be used to wait till page load?
1.Explicit Wait – Webdriver wait with expected conditions Statement is used to
wait till page load.
2. Fluent wait is also used to wait till page load.
Q.25. How to handle dynamic object?
Dynamic object is handled using dynamic xpath . Below are few common techniques used
to handle dynamic objects.
Syntax
//form/div[1]/div/div[1]/div/div/input[1]
• Using Single Attribute-You could write the syntax in two ways as mentioned below.
Including or excluding HTML Tag. If you want to exclude HTML Tag then you need
to use *
• Syntax
//<HTML tag>[@attribute_name='attribute_value']
OR
//*[@attribute_name='attribute_value']
Note: ‘*‘ after double slash is to match any tag with the desired text
• Using Multiple Attribute-
Syntax
//<HTMLtag>[@attribute_name1='attribute_value1'][@attribute_name2='attribute_valu
e2]
OR
//*[@attribute_name1='attribute_value1'][@attribute_name2='attribute_value2]
• Using AND
Syntax
//<HTML tag>[@attribute_name1='attribute_value1' and
@attribute_name2='attribute_value2]
OR
//<HTML tag>[@attribute_name1='attribute_value1' and
@attribute_name2='attribute_value2]
• Using OR-
Syntax
//<HTML tag>[@attribute_name1='attribute_value1' or
@attribute_name2='attribute_value2]
OR
//*[@attribute_name1='attribute_value1' or @attribute_name2='attribute_value2]
• Using contains()
It is used to identify an element, when we are familiar with some part of the
attributes value of an element.
Syntax
//<HTML tag>[contains(@attribute_name,'attribute_value')]
OR
//*[contains(@attribute_name,'attribute_value')]
• Using starts_with()
starts-with(): It is used to identify an element, when we are familiar with the
attributes value (starting with the specified text) of an element.
• Syntax
//<HTML tag>[starts-with(@attribute_name,'attribute_value')]
OR
//*[starts-with(@attribute_name,'attribute_value')]
• Using text()
text(): This mechanism is used to locate an element based on the text available on
a webpage
As per the above image, we could identify the elements text based on the below
xpath.
• Syntax
//*[text()='New look for sign-in coming soon']
• Using last()
last(): Selects the last element (of mentioned type) out of all input element present
To identify the element (last text field ) “Your current email address”, we could use
the below xpath.
- findElement(By.xpath("(//input[@type='text'])[last()]"))
[last()-1] – Selects the last but one element (of mentioned type) out of all input element
present
findElement(By.xpath("(//input[@type='text'])[last()-1]"))
• Using position()
position(): Selects the element out of all input element present depending on the
position number provided
In below given xpath, [@type=’text’] will locate text field and
function [position()=2] will locate text filed which is located on 2nd position from
the top.
findElement(By.xpath("(//input[@type='text'])[position()=2]"))
or
findElement(By.xpath("(//input[@type='text'])[2]"))
• Using index()
By providing the index position in the square brackets, we could move to the nth
element. Based on the below xpath, we could identify the Last Name field.
findElement(By.xpath("//label[2]"))
• Using following xpath axes
following: By using this we could select everything on the web page after the
closing tag of the current node
xpath of the FirstName field is as follows
//*[@id='FirstName']
To identify the input field of type text after the FirstName field, we need to use the
below xpath.
//*[@id='FirstName']/following::input[@type='text']
Here I used, following xpath axes and two colons and then specified the required tag (i.e.,
input)
To identify just the input field after the FirstName field, we need to use the below xpath.
//*[@id='FirstName']/following::input
• Using preceding xpath axes
preceding: Selects all nodes that appear before the current node in the document,
except ancestors, attribute nodes and namespace nodes
xpath of the LastName field is as follows
//*[@id='LastName']
To identify the input field of type text before the LastName field, we need to use the
below xpath.
//*[@id='LastName']//preceding::input[@type='text']"
Here I used, preceding xpath axes and two colons and then specified the required tag (i.e.,
input).
If you are not regular reader of my blog then I highly recommend you to signup for the
free email newsletter using the below link.
Q.26. Difference between thread wait, implicit wait, explicitwait?
Syntax
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
//Wait for the condition
.withTimeout(30, TimeUnit.SECONDS)
// which to check for the condition with interval of 5 seconds.
.pollingEvery(5, TimeUnit.SECONDS)
//Which will ignore the NoSuchElementException
.ignoring(NoSuchElementException.class);
1.selectByVisibleText
selectByVisibleText(String arg0) : void – It is very easy to choose or select an
option given under any dropdowns and multiple selection boxes with
selectByVisibleText method. It takes a parameter of String which is one of the Value
of Select element and it returns nothing.
Command – oSelect.selectByVisibleText(“text”);
2.selectByIndex
selectByIndex(int arg0) : void – It is almost the same as selectByVisibleText but the
only difference here is that we provide the index number of the option here rather
the option text.It takes a parameter of int which is the index value of Select
element and it returns nothing.
Command – oSelect.selectByIndex(int);
selectByValue
selectByValue(String arg0) : void –It is again the same what we have discussed
earlier, the only difference in this is that it ask for the value of the option rather the
option text or index. It takes a parameter of String which is on of the value of Select
element and it returns nothing.
Command – oSelect.selectByValue(“text”);
4.getOptions
getOptions( ) : List<WebElement> –This gets the all options belonging to the Select
tag. It takes no parameter and returns List<WebElements>.
Command – oSelect.getOptions();
DeSelect Methods-
deselectAll( ) : void – Clear all selected entries. This is only valid when the SELECT
supports multiple selections.
Command – oSelect.deselectAll;
deselectByIndex(int arg0) : void –Deselect the option at the given index.
Command – oSelect.deselectByIndex;
deselectByValue(String arg0) : void –Deselect all options that have a value matching the
argument.
Command – oSelect.deselectByValue;
deselectByVisibleText(String arg0) : void – Deselect all options that display text matching
the argument.
Command – oSelect.deselectByVisibleText
isMultiple( ) : boolean – This tells whether the SELECT element support multiple
selecting options at the same time or not. This accepts nothing but returns
booleanvalue(true/false).
Command – oSelect.isMultiple();
Q.29. List out all methods available in select class.
void deselectAll()
Clear all selected entries.
java.util.List<WebElement> getAllSelectedOptions()
WebElement getFirstSelectedOption()
java.util.List<WebElement> getOptions()
boolean isMultiple()
Ans: selectByVisibleText
oSelect.selectByVisibleText("2010");
selectByIndex
selectByValue
Ans: isMultiple
oSelect.isMultiple()
Select oSelect = new Select(driver.findElement(By.id(Element_ID)));
oSelect.selectByIndex(index)
34)How to select all the similar value from drop down Eg we have multiselect dropdown
like automation testing,manual testing sql testing we should all the option which
contains “testing”word?
Ans: By using select class Select by value method we can achive.
List<Webelement >listofdropdown=driver.findelements <by.id(“dropdown”));
Select select=new select(listofdropdown)
{
If(select.selectByvalue(“testing”)
{
System.out.println(list.getText());
elem = find_element_by_name("our_element")
elem.send_keys("bar")
elem.send_keys(Keys.CONTROL, 'a') #highlight all in box
elem.send_keys(Keys.CONTROL, 'c') #copy
elem.send_keys(Keys.CONTROL, 'v') #paste
I
39) Diffference between build() & perform()
Ans: Perform:: A convenience method for performing the actions without calling build()
first
To Perform Some Action you have to Call Build Before any Action like
click().build.perform(); // it is something like adding some Action to buffer from where
perform used to exceute that action
@Test
public void testDragAndDropExample() {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.navigate().to("http://jqueryui.com/droppable/");
//Wait for the frame to be available and switch to it
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelecto
r(".demo-frame")));
WebElement Sourcelocator = driver.findElement(By.cssSelector(".ui-
draggable"));
WebElement Destinationlocator = driver.findElement(By.cssSelector(".ui-
droppable"));
dragAndDrop(Sourcelocator,Destinationlocator);
String
actualText=driver.findElement(By.cssSelector("#droppable>p")).getText();
Assert.assertEquals(actualText, "Dropped!");
}
}
41. How to perform right click operation? Question on window handling
Answer: We can perform right click operation by using the context menu.
We will take the help of WebDriver action class and perform Right Click. The below is
the syntax :
Actions action = new Actions(driver).contextClick(element);
action.build().perform();
• GetWindowHandle Command
• GetWindowHandles Command
Purpose: WebDriver supports moving between named windows using the “switchTo”
method.
driver.switchTo().window("windowName");
Or
Alternatively, you can pass a “window handle” to the “switchTo().window()” method.
Knowing this, it’s possible to iterate over every open window like so:
for (String handle : driver.getWindowHandles()) {
driver.switchTo().window(handle);
}
• Switching between windows with Iterators:
driver.findElement(By.id(“id of the link which opens new window”)).click();
//wait till two windows are not opened
waitForNumberofWindowsToEqual(2);//this method is for wait
Set handles = driver.getWindowHandles();
firstWinHandle = driver.getWindowHandle(); handles.remove(firstWinHandle);
String winHandle=handles.iterator().next();
if (winHandle!=firstWinHandle){
//To retrieve the handle of second window, extracting the handle which does not match to
first window handle
secondWinHandle=winHandle; //Storing handle of second window handle
//Switch control to new window
driver.switchTo().window(secondWinHandle);
43. How to work with new tab new browse window with our GetWindowHandles
method?
Answer:You can switch between windows as below:
// Store the current window handle
String winHandleBefore = driver.getWindowHandle();
// Perform the click operation that opens new window
// Switch to new window opened
for(String winHandle : driver.getWindowHandles()){
driver.switchTo().window(winHandle);
}
// Perform the actions on new window
Web-Based alert and Java Script alerts are same so do not get confused.
Until you do not handle alert window you cannot perform any action in the parent window.
2. Confirmation Popup
Confirmation popup displays on page of software web application with confirmation
text, Ok and Cancel button as shown In bellow given Image.
3. Prompt alertPopup
Prompts will have prompt text, Input text box, Ok and Cancel buttons.
In the web page sometimes you’ll fail to inspect a particular element, in that time, go to
firebug window in the firebug toolbar and select the firbug search symbol.
Here is an example which shows how to handle calendar pop up :
1) Launch Eclipse, create a project, a package, and a class under named “test1.java”.
2) Navigate to site “http://www.makemytrip.com/”. For this you need to add the following
lines of code in your script :
WebDriver driver=new FirefoxDriver();
driver.get(“http://www.makemytrip.com/”);
3) Right click on the calendar option given for Departure and inspect it. Chose the date of
departure as 3rd March. To do this much you need to include the following lines of code in
your script :
driver.findElement(By.id(“start_date_sec”)).click();
driver.findElement(By.xpath(“//*[@id=’ui-datepicker-
div’]/div[3]/table/tbody/tr[1]/td[3]/a”)).click();
4) Now again click on the Departure Calendar and click on the Cross button(X) to close the
calendar. For this, first locate the calendar and then click on it.
driver.findElement(By.id(“start_date_sec”)).click();
driver.findElement(By.xpath(“//*[@id=’ui-datepicker-div’]/div[5]/button[2]”)).click();
This is all about calendar pop up. Handling Calendar pop up is not complex. All you have
to do is locate the element and locate it correctly, then perform action…!!!
46. How to work with advertisement pop-up?
Answer:
Some times when we browsing software web application, Display some unexpected alerts
due to some error or some other reasons. This kind of alerts not display every time but
they are displaying only some time. If you have created webdriver software
automation test case for such page and not handled this kind of alerts In your code
then your script will fail Immediately If such unexpected alert pop up displayed.
To handle this kind of unexpected alerts, You must at least aware about on which action
such unexpected alert Is generated. Sometimes, They are generated during software web
application page load and sometime they are generated when you perform some action. So
first of all we have to note down the action where such unexpected alert Is generated and
then we can check for alert after performing that action. We need to use try catch block for
checking such unexpected alters because If we will use direct code(without try catch) to
accept or dismiss alert and If alert not appears then our test case will fail. try catch can
handle both situations.
I have one example where alert Is displaying when loading software web page. So we can
check for alert Inside try catch block after page load as shown In bellow given example.
After loading page, It will check for alert. If alert Is there on the page then It will dismiss It
else It will go to catch block and print message as shown In bellow given example.
Run bellow given example In eclipse with testng and observe the result.
package Testng_Pack;
public class unexpected_alert {
WebDriver driver = null;
@BeforeTest
public void setup() throws Exception {
System.setProperty("webdriver.gecko.driver", "D:\\Selenium Files\\geckodriver.exe");
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/06/alert_6.html");
}
@AfterTest
public void tearDown() throws Exception {
driver.quit();
}
@Test
public void Text() throws InterruptedException {
//To handle unexpected alert on page load.
try{
driver.switchTo().alert().dismiss();
}catch(Exception e){
System.out.println("unexpected alert not present");
}
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("fname");
driver.findElement(By.xpath("//input[@name='lname']")).sendKeys("lname");
driver.findElement(By.xpath("//input[@type='submit']")).click();
}
}
SSL is used to keep sensitive information which is sent across the Internet encrypted so
that only the intended recipient understand it. This is important because, the information
that we send on the internet is passed from one system to other system to the destination
server.
If it is not encrypted with an SSL certificate, any computer in between you and the
destination server can see your private information such as credit card numbers,
usernames, passwords and other sensitive information.
The above listed errors are the common errors, you may come across other errors which
actually depends on the websites that you access.
Now Let us seehow to handle SSL Untrusted Connection and Accept with Selenium
webdriver. Let me try to do with Firefox browser
We will create new firefox profile and set 'setAcceptUntrustedCertificates' as true and
setAssumeUntrustedCertificateIssuer as false.
package com.example;
publicclassSSLExample {
@Test
publicvoidopenApplication() {
System.out.println("Navigating application");
driver.get("https://cacert.org/");
WebElement headingEle = driver.findElement(By.cssSelector(".story
h3"));
//Validate heading after accepting untrusted connection
String expectedHeading = "Are you new to CAcert?";
Assert.assertEquals(headingEle.getText(), expectedHeading);
}
@AfterClass
publicvoidtearDown() {
if(driver!=null)
driver.quit();
}
}
Done. You have now accepted the SSL Certificate with Selenium webdriver.
Answer:
Now selenium webdriver software automation testing tool do not have any feature to
handle this save file dialogue. But yes, Selenium webdriver has one more very good
feature by which you do not need to handle that dialogue and you can download any file
very easily. We can do It using webdriver's Inbuilt class FirefoxProfile and Its different
methods. Before looking at example of downloading file, Let me describe you some thing
about file's MIME types. Yes you must know MIME type of file which you wants to
download using selenium webdriver software testing tool.
You need to provide MIME type of file In your selenium webdriver test so that you must
be aware about It. There are many online tools available to know MIME type of any file.
Just google with "MIME checker" to find this kind of tools.
In our example given bellow, I have used MIME types as shown bellow for different file
types In bellow given selenium webdriver test.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
@BeforeTest
public void StartBrowser() {
//Create object of FirefoxProfile in built class to access Its properties.
FirefoxProfile fprofile = new FirefoxProfile();
//Set Location to store files after downloading.
fprofile.setPreference("browser.download.dir", "D:\\WebDriverdownloads");
fprofile.setPreference("browser.download.folderList", 2);
//Set Preference to not show file download confirmation dialogue using MIME types
Of different file extension types.
fprofile.setPreference("browser.helperApps.neverAsk.saveToDisk",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;"//MIME types
Of MS Excel File.
+ "application/pdf;" //MIME types Of PDF File.
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document;"
//MIME types Of MS doc File.
+ "text/plain;" //MIME types Of text File.
+ "text/csv"); //MIME types Of CSV File.
fprofile.setPreference( "browser.download.manager.showWhenStarting", false );
fprofile.setPreference( "pdfjs.disabled", true );
//Pass fprofile parameter In webdriver to use preferences to download file.
System.setProperty("webdriver.gecko.driver", "D:\\Selenium Files\\geckodriver.exe");
driver = new FirefoxDriver(fprofile);
}
@Test
public void OpenURL() throws InterruptedException{
driver.get("http://only-testing-blog.blogspot.in/2014/05/login.html");
//Download Text File
driver.findElement(By.xpath("//a[contains(.,'Download Text File')]")).click();
Thread.sleep(5000);//To wait till file gets downloaded.
//Download PDF File
driver.findElement(By.xpath("//a[contains(.,'Download PDF File')]")).click();
Thread.sleep(5000);
//Download CSV File
driver.findElement(By.xpath("//a[contains(.,'Download CSV File')]")).click();
Thread.sleep(5000);
//Download Excel File
driver.findElement(By.xpath("//a[contains(.,'Download Excel File')]")).click();
Thread.sleep(5000);
//Download Doc File
driver.findElement(By.xpath("//a[contains(.,'Download Doc File')]")).click();
Thread.sleep(5000);
}
@AfterTest
public void CloseBrowser() {
driver.quit();
}
}
When you run above example, It will download all 5(Text, pdf, CSV, docx and xlsx) files
one by one and store them In D:\WebDriverdownloads folder automatically as shown In
bellow given example.
; wait for 8 seconds to appear download and save dialog. Used class property of
download dialog.
WinWait("[CLASS:#MozillaDialogClass]","",8)
; Perform keyboard ALT key down + s + ALT key Up action to select Save File Radio
button using keyboard sortcut.
Send("{ALTDOWN}s{ALTUP}")
Now you can create executable file of above script as described In THIS POST. After
conversion, you will get executable file "Script To Download File.exe".
CLICK HERE to download ready made "Script To Download File.au3" and "Script To
Download File.exe" files of AutoIt.
So our Selenium webdriver + AutoIt script to download file from web page Is as bellow.
Note : "Script To Download File.exe" file should be located at E:\\AutoIT folder.
package AutoIt;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
@BeforeTest
public void setup() throws Exception {
driver =new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/05/login.html");
}
@Test
public void testCaseOne_Test_One() throws IOException, InterruptedException {
//Click on Download Text File link to download file.
driver.findElement(By.xpath("//a[contains(.,'Download Text File')]")).click();
//Execute Script To Download File.exe file to run AutoIt script. File location =
E:\\AutoIT\\
Runtime.getRuntime().exec("E:\\AutoIT\\Script To Download File.exe");
}
}
Now If you run above script, It will download Text file automatically. At the end of script
execution, file will be downloaded as shown In bellow Image.
This way you can download any file from web page.
There are different methods which robot class uses. Here in the below example we have
used 'keyPress' and 'keyRelease' methods.
Both the above methods Throws - IllegalArgumentException, if keycode is not a valid key.
We have defined two methods in the below example along with the test which is used to
upload a file.
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection,
null);
}
public static void uploadFile(String fileLocation) {
try {
//Setting clipboard with file location
setClipboardData(fileLocation);
//native key strokes for CTRL, V and ENTER keys
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
} catch (Exception exp) {
exp.printStackTrace();
}
}
}
OR
• Using JAVA script executor
1. We can scroll down vertically by using the following code:
2. ((JavascriptExecutor) driver).executeScript("scroll(0,250);");
3. Similarly, it is also possible to scroll up by changing y coordinate as
negative:
4. ((JavascriptExecutor) driver).executeScript("scroll(0, -250);");
5. You can also use the following code: For scroll down:
d.switchTo().defaultContent();
d.switchTo().frame(1);
Or
55. How to work with multiple windows?
We can handle multiple windows in selenium webdriver using “Switch To” methods
which will allow us to switch control from one window to another window.
String parent=driver.getWindowHandle();
Set<String>s1=driver.getWindowHandles();
Iterator<String> I1= s1.iterator();
while(I1.hasNext())
{
String child_window=I1.next();
if(!parent.equals(child_window))
{
driver.switchTo().window(child_window);
System.out.println(driver.switchTo().window(child_window).getTitle());
driver.close();
}
}
//First we will find the iFrame , then we will switch to command.
WebElement frame = driver.findElement(By.Name("frame1"));
//Now we will switch focus,
driver.switchTo().frame("frame");
56. How many ways to work with frames?
→Following are the possible ways for handling Frames
webdriver.switchTo().frame("frame name/value");
webdriver.switchTo().frame(index);
Note: finally if you want to make operation out of the frame first you need get out of
the frame following is the statement for that
driver.switchTo().defaultContent();
57. How to work on frame, if we don’t have ID or Web Element
→ we must find the index of the iframe through which the element is being loaded
and then we need to switch to the iframe through the index.
int size = driver.findElements(By.tagName("iframe")).size();
the above code finds the total number of iframes present inside the page using the
tagname 'iframe'.
Now, finding out the index of iframe.
for(int i=0; i<=size; i++){
driver.switchTo().frame(i);
int total=driver.findElements(By.xpath("html/body/a/img")).size();
System.out.println(total);
driver.switchTo().defaultContent();
}
58. What is illegal state exception?
→
→Path to the folder where you have extracted the IEDriver executable file
String service = "D:\\ToolsQA\\trunk\\Library\\drivers\\IEDriverServer.exe";
System.setProperty("webdriver.ie.driver", service);
InternetExplorerDriver driver = new InternetExplorerDriver();
driver.get("http://demoqa.com");
60. How to write xpath in IE and Chrome browser?
→ Step #1: For creating XPath in Developer tool, open the console tab.
Step #2: Type the created Xpath and enclose it in $x(“//input[@id=’Email’]”)
Resources - Copy the resources to the output directory for including in the JAR.
Verifier - Useful for integration tests - verifies the existence of certain conditions.
4. JENKINS
Q.96What is Jenkins?
Xpath
Xpath is a query language for selecting nodes from an XML document.While DOM is the
recognized standard for navigation through an HTML element tree, XPath is the standard
navigation tool for XML.XPath is used everywhere where there is XML. XPath is a very
powerful language to express which element to identify.If you use it correctly, it can
produce very reliable and low maintenance locators, but if you use it incorrectly, it can
create very brittle test cases.
Pros:
–Allows very precise locators
Cons:
–Slower than CSS
–Relies on browser’s XPath implementation which is not always complete (especially on
IE) and as such is not –recommended for cross-browser testing.
Absolute path:
driver.findElement(By.xpath("html/body/div/p/input"));
Relative path:
driver.findElement(By.xpath("input"));
ccsSelector
The CSS locator strategy uses CSS selectors to find the elements in the page. Selenium
supports CSS 1 through 3 selectors syntax excepted CSS3 namespaces.Browsers
implement CSS parsing engines for formatting or styling the pages using CSS syntax.
Pros:
–Much faster than XPath
–Widely used
–Provides a good balance between structure and attributes
–Allows for selection of elements by their surrounding context
Cons:
–They tend to be more complex and require a steeper learning curve.
Examples:
Absolute Path:
driver.findElement(By.cssSelector("html>body>div>p>input"));
Relative Path:
driver.findElement(By.cssSelector("input"));
Regular Attribute:
driver.findElement(By.cssSelector("button[name='cancel']")); (tag with attribute value)