Saturday, January 18, 2014
Thursday, January 16, 2014
Running Selenium Script from command prompt using .class instead of .java file - TestNG
Sometimes we need to run our automation script at client machine to demonstrate
our ability to automate but we don't want to share our code without JDK (required
- JRE). We can achieve this by following below steps. With this we can run the
script from .class instead of .java file.
We can achieve this using both JUnit and TestNG. In this example we are working with TestNG.
Here my example is GoogleSearch.java
Step 1: Prepare required script using any IDE (eclipse) and compile
Step 2: Open command prompt in another system and check whether JRE is available
Step 3: Prepare testng.xml file as follows
< !DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Google">
<test name="GoogleSearch">
<classes>
<class name="GoogleSearch"/>
</classes>
</test>
</suite>
Step 3: Copy selenium standalone server, TestNG.jar, .class and testng.xml files to a folder(D:\Google\)
Step 4: Open command prompt and change to D:\Google\
Step 5: Set path using the following command
set classpath=%classpath%;D:\Google\selenium-server-standalone-2.39.0.jar;D:\Google\testng-6.8.jar;.;
*Note: update the paths of the .jar files and .class file according to your path.
Step 6: Run the class file using the following command
java org.testng.TestNG java org.testng.TestNG testng.xml
Now, you can see the bowser will open and perform the required operation without code and eclipse.
We can achieve this using both JUnit and TestNG. In this example we are working with TestNG.
Here my example is GoogleSearch.java
Step 1: Prepare required script using any IDE (eclipse) and compile
Step 2: Open command prompt in another system and check whether JRE is available
Step 3: Prepare testng.xml file as follows
< !DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Google">
<test name="GoogleSearch">
<classes>
<class name="GoogleSearch"/>
</classes>
</test>
</suite>
Step 3: Copy selenium standalone server, TestNG.jar, .class and testng.xml files to a folder(D:\Google\)
Step 4: Open command prompt and change to D:\Google\
Step 5: Set path using the following command
set classpath=%classpath%;D:\Google\selenium-server-standalone-2.39.0.jar;D:\Google\testng-6.8.jar;.;
*Note: update the paths of the .jar files and .class file according to your path.
Step 6: Run the class file using the following command
java org.testng.TestNG java org.testng.TestNG testng.xml
Now, you can see the bowser will open and perform the required operation without code and eclipse.
Class path Setup for Java - Windows
We all know the importance of CLASSPATH for
Java. Setting PATH/CLASSPATH is very easy but some of us facing difficulties.
For them I want to contribute from my blog. Following steps will provide how
easy we can set CLASSPATH/PATH for Java.
Step 1: Download and install Java if not available on your machine. You can download from the following URL: http://www.oracle.com/technetwork/java/javase/downloads/index.html
Step 1: Download and install Java if not available on your machine. You can download from the following URL: http://www.oracle.com/technetwork/java/javase/downloads/index.html
Step 3: Go to JDK installed location and you will find bin folder and open that one. Copy the bin folder path.
Step 5: Once Advance System Settings window is opened click on Environment Variables option
Step 6: Once Environment Variables window
is opened click on New underSystem Variablesand
enter Variable Name asPATH andVariable Valuesas Path of Java Bin Folder (previously
copied path) and click OK
Step 7: Go to JDK folder -> open lib folder and copy the path
Step 7: Go to JDK folder -> open lib folder and copy the path
Step 8: Repeat the steps 4 and 5. Now click
on New underUser Variablesand
enter User Variable asCLASSand Variable Values as
Path of the lib folder and click on OK .
Step
9: Click on OK of Environment Variables window and System Properties windowStep 10: Open Command Prompt and run any java program and you are able to successfully complete.
Select Auto suggest on search field for a List item using WebDriver
The below code is for searching a text automatically from the auto
suggest; mainly for a list item.
Thread.sleep(3000);
List <WebElement> listItems = driver.findElements(By.xpath("//div[@class='acResults']//li"));
// List <WebElement> listItems =
driver.findElements(By.xpath("//div[contains(@class,'acResults')]//li"));
driver.get("http://www.indiabookstore.net");
driver.findElement(By.id("searchBox")).sendKeys("Alche");Thread.sleep(3000);
List <WebElement> listItems = driver.findElements(By.xpath("//div[@class='acResults']//li"));
//List <WebElement> listItems =
driver.findElements(By.cssSelector(".acResults li"));
// List<WebElement> link = driver.findElement(By.id("Element")).findElements(By.tagName("li"));
listItems.get(0).click();
driver.findElement(By.id("searchButton")).click();
NOTE: get(0) is the first option displayed on searching keywords
get(1) is the second option
displayed on searching keywords.Print Eclipse IDE console output on a text file after Test execution
Following setting will print your eclipse console output on a separate
Text file.
1. Create a text file (.txt) in your project folder
2. In Eclipse, right click Project > Run configurations
3. Click the Tab, "Common"
4. Select the Check boxes, File & Append
5. Now, choose the correct directory and select the empty text file you created before
6. Click OK
7. Run the Test.
1. Create a text file (.txt) in your project folder
2. In Eclipse, right click Project > Run configurations
3. Click the Tab, "Common"
4. Select the Check boxes, File & Append
5. Now, choose the correct directory and select the empty text file you created before
6. Click OK
7. Run the Test.
Page Scroll using Selenium WebDriver
Scroll Down:
WebDriver driver = new
FirefoxDriver();
JavascriptExecutor jse =
(JavascriptExecutor)driver;
jse.executeScript("scroll(0, 250)"); //y value '250' can be altered
(or)
break;
}
}
if(second >=60){
break;
}
}
((JavascriptExecutor)driver).executeScript("window.scrollBy(0,"+(hoverItem.getY())+");");
// Adjust your page view by making changes right over here (hoverItem.getY()-400)
coordinate.onPage();
coordinate.inViewPort();
import
org.openqa.selenium.JavascriptExecutor;
jse.executeScript("scroll(0, 250)"); //y value '250' can be altered
Scroll up:
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("scroll(250, 0)");
//x value '250' can be altered
Scroll bottom of the Page:
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.scrollTo(0,Math.max(document.documentElement.scrollHeight,
document.body.scrollHeight, document.documentElement.clientHeight));");(or)
Actions actions = new
Actions(driver);
actions.keyDown(Keys.CONTROL).sendKeys(Keys.END).perform();
Full scroll to bottom in slow
motion:
for (int second = 0;; second++) {
if(second >=60){break;
}
((JavascriptExecutor)
driver).executeScript("window.scrollBy(0,400)", ""); //y
value '400' can be altered
Thread.sleep(3000);}
(or)
JavascriptExecutor jse =
(JavascriptExecutor)driver;
for (int second = 0;; second++)
{if(second >=60){
break;
}
jse.executeScript("window.scrollBy(0,800)", ""); //y
value '800' can be altered
Thread.sleep(3000);}
Scroll automatically to your
WebElement:
Point hoverItem
=driver.findElement(By.xpath("Value")).getLocation();
((JavascriptExecutor)driver).executeScript("return
window.title;");
Thread.sleep(6000);((JavascriptExecutor)driver).executeScript("window.scrollBy(0,"+(hoverItem.getY())+");");
// Adjust your page view by making changes right over here (hoverItem.getY()-400)
(or)
((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();",
driver.findElement(By.xpath("Value')]")));
(or)
WebElement element =
driver.findElement(By.xpath("Value"));
Coordinates coordinate =
((Locatable)element).getCoordinates(); coordinate.onPage();
coordinate.inViewPort();
Selenium Basics & Tips
1.
Maximize Firefox browser window using selenium
webdriver
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
3. Get current web page URL
System.out.println(driver.getCurrentUrl());
4. Navigate Back | Forward & Page refresh
Navigate Back
Webdriver driver = new FirefoxDriver();
driver.navigate().back();
5. Highlighting Elements
WebElement element1 = driver.findElement(By.className("Value"));
WebElement element2 = driver.findElement(By.id("Value"));
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("arguments[0].setAttribute('style', arguments[1]);", element1, "color: blue; border: 2px solid blue;");
6. Double-click WebElement
action.perform();
7. Delete All Cookies
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
2. Customize
browser window size
driver.manage().window().setSize(new
Dimension(320, 480));3. Get current web page URL
System.out.println(driver.getCurrentUrl());
4. Navigate Back | Forward & Page refresh
Navigate Back
Webdriver driver = new FirefoxDriver();
driver.navigate().back();
(or)
Actions actions = new
Actions(driver);
actions.sendKeys(Keys.BACK_SPACE).perform();
Navigate Forward
driver.navigate().forward();
Page Refresh
driver.navigate().refresh();
(or)
Actions actions = new
Actions(driver);
actions.keyDown(Keys.CONTROL).sendKeys(Keys.F5).perform();5. Highlighting Elements
WebElement element1 = driver.findElement(By.className("Value"));
WebElement element2 = driver.findElement(By.id("Value"));
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("arguments[0].setAttribute('style', arguments[1]);", element1, "color: blue; border: 2px solid blue;");
jse.executeScript("arguments[0].setAttribute('style',
arguments[1]);", element2, "color: yellow; border: 0px solid
red;");
6. Double-click WebElement
Actions action = new Actions(driver);
action.doubleClick(driver.findElement(By.id("Value")));
action.perform();
7. Delete All Cookies
driver.manage().deleteAllCookies();
Configure TestNG with Eclipse
Steps to Configure TestNG with
Eclipse:
3. In the ‘Name’ column we can see “TestNG” –> Select this and click ‘Next’ button
4. Click Next and click on the radio button “I accept the terms of the license agreement”.
5. Click ‘Next’ button
6. Click ‘Finish’
1. Click Help –> Install New Software
2. Type “http://beust.com/eclipse” in the “Work with” edit box and
click ‘Add’ button.3. In the ‘Name’ column we can see “TestNG” –> Select this and click ‘Next’ button
4. Click Next and click on the radio button “I accept the terms of the license agreement”.
5. Click ‘Next’ button
6. Click ‘Finish’
•This will install the TestNG plug-in for Eclipse
•After the installation, it will
ask for restart of Eclipse. Then restart
the Eclipse.
•Once the Eclipse is restarted,
we can see the TestNG icons & menu items.
Setting up Selenium & Eclipse
Configure Selenium with Eclipse:
1. Go to URL – http://www.eclipse.org/downloads/
2. Download Eclipse IDE for Java Developers (Click on Windows 32 bit platform)
3. Unzip Eclipse and double click Eclipse.exe
4. Create a workspace folder –> C:\Workspace (or)
5. Click File menu –> Switch Worspace –> other
6. Now Select the C:\Workspace folder.
7. Click Workbench.
1. Download Selenium server
2. Download Selenium Client driver
2. In Select Wizard –> Click Java –> “Java Project”
3. Give the project name (e.g. TestProject)
4. Click Finish.
5. Create a folder named “lib” inside the project "TestProject".
6. Copy the jar file "Selenium-server.jar" into "lib" folder.
7. Also extract all the jar files from "selenium-java-x.xx.x" (Selenium Client driver) into "lib" folder.
8. Right Click the project, “TestProject” and click "Build Path".
9. Select "Configure Build Path".
10. Click Libraries tab
11. Click “Add External JARs” button
12. Now, select all the jar files copied under the "lib" folder.
13. Click OK
14. Check the Referenced libraries for both the Selenium Client driver jar files.
3. Right click on the Package and Click File –> New –> class
4. Name the class. (e.g., Test)
5. Now write the script and run it.
1. Go to URL – http://www.eclipse.org/downloads/
2. Download Eclipse IDE for Java Developers (Click on Windows 32 bit platform)
3. Unzip Eclipse and double click Eclipse.exe
4. Create a workspace folder –> C:\Workspace (or)
5. Click File menu –> Switch Worspace –> other
6. Now Select the C:\Workspace folder.
7. Click Workbench.
Download Drivers
Now, download Selenium RC server/client driver and configure that to
Eclipse.1. Download Selenium server
2. Download Selenium Client driver
Configure Selenium Client driver
1. Go to Eclipse –> Click File
–> New –> Project (from various options need to select just “project”)2. In Select Wizard –> Click Java –> “Java Project”
3. Give the project name (e.g. TestProject)
4. Click Finish.
5. Create a folder named “lib” inside the project "TestProject".
6. Copy the jar file "Selenium-server.jar" into "lib" folder.
7. Also extract all the jar files from "selenium-java-x.xx.x" (Selenium Client driver) into "lib" folder.
8. Right Click the project, “TestProject” and click "Build Path".
9. Select "Configure Build Path".
10. Click Libraries tab
11. Click “Add External JARs” button
12. Now, select all the jar files copied under the "lib" folder.
13. Click OK
14. Check the Referenced libraries for both the Selenium Client driver jar files.
Create class file
1. Right click on the folder
"src", Click File –> New
–> Package
2. Name the Package. (e.g., testpack) and click Finish.3. Right click on the Package and Click File –> New –> class
4. Name the class. (e.g., Test)
5. Now write the script and run it.
Taking Screenshot and Saving Screenshot (WebDriver)
Snippet for taking screenshot and saving it in specified path,
import java.io.File;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.apache.commons.io.FileUtils;
@Test
public void myTest() throws
Exception {
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
import java.io.File;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.apache.commons.io.FileUtils;
driver.get("http://www.google.com");
driver.findElement(By.name("q")).sendKeys("Selenium");File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("F:\\Screenshots\\webscreen1.png"));
}Handling frame in WebDriver
Snippet for handling frame in webdriver,
WebElement frame1=driver.findElement(By.className(“framepd”));
WebElement frame1=driver.findElement(By.className(“framepd”));
Driver.switchTo().frame(frame1);
Driver.findElement(By.id(“txtCode”)).sendKeys(“12345”);
Handling Mouse Over in WebDriver
Snippet for handling Mouse over,
Actions actions=new Actions(driver);
Actions actions=new Actions(driver);
WebElement mouseOver=driver.findElement(By.id("aBills"));
actions.moveToElement(mouseOver, 10,
10).perform();
Handling Alerts (WebDriver)
Snippet for Handling Alerts
Package Required for Alert-----> import org.openqa.selenium.Alert;
getText()
alert.accept();
//alert.dismiss();
Package Required for Alert-----> import org.openqa.selenium.Alert;
Alert class provides various methods such as:
accept()
dismiss()getText()
Alert alert = driver.switchTo().alert();
System.out.println(alert.getText());alert.accept();
//alert.dismiss();
How to switch control to pop-up window?
If you want to do any operations in pop-up window you need to switch
the control to pop-up window then do all your operations in that and finally
close the pop-up window and again select the default (main ) window.
Here is WebDriver logic to select Pop-up window
driver.switchTo().window("<window name>");
String mainWindowHandle=driver.getWindowHandle();
Open the pop-up (click on element which causes open a new window)
webElement.click();
while(ite.hasNext())
{
String popupHandle=ite.next().toString();
if(!popupHandle.contains(mainWindowHandle))
{
driver.switchTo().window(popupHandle);
}
}
Here is WebDriver logic to select Pop-up window
1. Pop-up window has name/id
driver.switchTo().window("<window name>");
2. Pop-up window doesn't have name / you don't want to hard code the
window name then go for below logic.
Before opening pop-up get the main window handle.String mainWindowHandle=driver.getWindowHandle();
Open the pop-up (click on element which causes open a new window)
webElement.click();
Try to get all available open window handles with below command. (The
below command returns all window handles as Set)
Set s =
driver.getWindowHandles();
From that above set try to get newly opened window and switch the
control to that (pop-up window handle), as we already know the
mainWindowHandle.
Set s =
driver.getWindowHandles();
Iterator ite = s.iterator();while(ite.hasNext())
{
String popupHandle=ite.next().toString();
if(!popupHandle.contains(mainWindowHandle))
{
driver.switchTo().window(popupHandle);
}
}
Read Data or HTML table Using WebDriver
Code Snippet for how to Read Data or HTML table Using WebDriver
WebElement tab=driver.findElement(By.xpath("//table[@id='availabilityTable1']"));
List<WebElement> tableRows = tab.findElements(By.tagName("tr"));
{
for (WebElement cell:tableRows)
{
List<WebElement>data=cell.findElements(By.xpath("//td[5]"));
//Reading 5th Column of the Table
for(WebElement d:data)
{
System.out.println(d.getText());
}
WebElement tab=driver.findElement(By.xpath("//table[@id='availabilityTable1']"));
List<WebElement> tableRows = tab.findElements(By.tagName("tr"));
{
for (WebElement cell:tableRows)
{
List<WebElement>data=cell.findElements(By.xpath("//td[5]"));
//Reading 5th Column of the Table
for(WebElement d:data)
{
System.out.println(d.getText());
}
Waits in WebDriver (Implicit, Explicit and ThreadSleep)
Implicit Wait - It's global
setting applicable for all elements and if element appear before specified time
than script will start executing otherwise script will throw
NoSuchElementException.
In Explicit you can configure, how frequently (instead of 2 seconds) you want to check condition
Using Thread.sleep(2000); is an unconditional wait. If your test loads faster you will still have to wait. So in principle using implicitlyWait is the better solution.
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10,
TimeUnit.SECONDS);
In this case, User is telling WebDriver that it should wait 10 seconds
in case of specified element is not available on the UI i.e (DOM).
NOTE: Implicit wait time is
applied to all elements in your script
Explicit wait
WebDriverWait wait=new WebDriverWait(driver,50);
wait.until(ExpectedConditions.textToBePresentInElement(By.id("ID
OF TEXT BOX")));
Using explicit waits you are basically telling WebDriver at the max it
is to wait for X units of time before it gives up.
Explicit wait time is applied only for particular specified element.In Explicit you can configure, how frequently (instead of 2 seconds) you want to check condition
ThreadSleep
Using Thread.sleep(2000); is an unconditional wait. If your test loads faster you will still have to wait. So in principle using implicitlyWait is the better solution.
Database Testing Checklist
1.) Data Integrity
c.) Is the data present in the correct table?
d.) Is the data present in correct field within the table?
c.) SQL Injection should not be allowed and handled properly
d.) Backup and Recovery: Is timely backup of Database taken.
e.) Security: Is the data secured from unauthorized access: Are different user roles created with different permissions Do all the users have access on Database
f.) Is the Field length specified on UI same as field length specified in table to store same element from UI into database.
g.) Check for Primary key: For Primary key 'Allow Null' condition should not be allowed.
h.) Check for each field and UI element: Field length of field in data base and on UI(if mentioned) should be same.
The complete data belonging to each entity should be stored in the
database.
Depending on the database design, the data may be present in a single
table or multiple related tables. Parent-child relationships should exist in
the data. There should not be any missing data.
a.) Is the data stored in tables is correct?
b.) Is there any unnecessary data present?c.) Is the data present in the correct table?
d.) Is the data present in correct field within the table?
2.) Database Performance
(query execution times, throughput etc.) and locking problems
You may identify the main queries (or procedures) that are used in the application
and time them with sample data. Locking problems may become apparent when
multiple inserts/ updates are being made to the same entity simultaneously.
3.) Data Security
You may check if any data that should be encrypted e.g. passwords,
credit card numbers is in plain text or not. The database should not have the
default passwords. Even application accounts should have passwords that are
complex and not easily guessed.
Miscellaneous
a.) Are the log events added in database for all login events?
b.) Does scheduled jobs execute timely.c.) SQL Injection should not be allowed and handled properly
d.) Backup and Recovery: Is timely backup of Database taken.
e.) Security: Is the data secured from unauthorized access: Are different user roles created with different permissions Do all the users have access on Database
f.) Is the Field length specified on UI same as field length specified in table to store same element from UI into database.
g.) Check for Primary key: For Primary key 'Allow Null' condition should not be allowed.
h.) Check for each field and UI element: Field length of field in data base and on UI(if mentioned) should be same.
STLC (Software Testing Life Cycle)
Software Testing Life Cycle (STLC) is a very important concept that
we need to know if we wants to understand testing process in detail. Many
people think testing is a static task and finds it boring, but it is definitely
not. STLC shows the different phases which are essential for quality control of
any software project.
3. Test Designing
4. Test Environment Setup
5. Test Execution
6. Test Closure
Every company follows its own Software Testing Life Cycle. STLC is
affected by the Software Development Life Cycle (SDLC) implemented by the
company as well as the management’s views towards Quality Assurance &
Control activities.
1. Requirement Analysis/Review
2. Test Planning3. Test Designing
4. Test Environment Setup
5. Test Execution
6. Test Closure
1.) Requirement Analysis
During this phase, test team studies the requirements from a testing
point of view to identify the testable requirements. The QA team may interact
with various stakeholders (Client, Business Analyst, Technical Leads, and
System
Architects etc) to understand the requirements in detail.
Requirements could be either Functional (defining what the software must do) or
Non Functional
(defining system performance /security availability )
2.) Test Planning
In this phase the QA/QA
Lead/QA Manager plans for the complete testing process. Important documents
like Test Strategy, Test Plan and Effort Estimation are derived from this
phase.
Everything regarding testing like selection of the testing tools,
test efforts estimations, planning resources, determining roles and
responsibilities of the personnel involved in the process, planning for the
training required, etc. are decided in this phase.
3.) Test Designing
Creation, Review & Update
of Test Cases as well as Test Scripts are done in this phase. The test cases
prepared by the QA team are reviewed and approved.
Test data may also be created in this phase by the QA team if test
environment is available to them.
If automation testing needs to be done then automation scripts also
needs to be written in this phase.
4.) Test Environment Setup
Test Environment is the actual
system/environment/setup where the testing team will be testing the
application. Test environment is prepared by understanding the required system
architecture, software & hardware requirements, etc.
Many times it happens that testing team is not involved in setting up
the test environment. In such scenarios, it is preferable that the testing team
should implement Smoke Testing to verify the readiness of the test environment
before starting the actual testing.
5.) Test Execution
During this phase test team
will carry out the testing based on the test plans and the test cases prepared
different testing techniques as well as methods are implemented and executed on
the software/application to break the system and find bugs.
Bugs will be reported to the development team, then development team
resolves the bugs and the system is retested to ensure that it is bug free and
ready to go live.Monday, January 6, 2014
Selenium tricks for CSS and Xpath locators
In this post you will learn some CSS rules and how to use CSS selectors and Xpath locators in Selenium.
(1) Id:
An element's id is defined as "[@id='idName']" in Xpath but "#idName" in CSS.
For example, a 'div' element with id 'panel' will be represented as below:
In Xpath locator
//div[@id='panel']In CSS selector
css=div#panel
(2) Class:
An element's class is defined as "[@class='className']" in Xpath but ".className" in CSS.
For example, a 'div' element with class 'panelClass' will be represented as below:
In Xpath locator
//div[@class='panelClass']In CSS selector
css=div.panelClassFor element with multiple class we need to separate with space(" ") in Xpath and dot(".") in case of CSS. See below example,
In Xpath locator
//div[@class='panelClass1 panelClass2']In CSS selector
css=div.panelClass1.panelClass2
(3) Any Attributes:
For selecting an element by its any of the attribute(say "name" is an attribute of a 'div' element and "type" in an "input" element) is given below:
In Xpath locator
//div[@name='continue']
//input[@type='button']In CSS selector
css=div[name='continue']
css=input[type='button']
(4) Direct Child:
A direct child of an element is denoted as "/" in Xpath and ">" in CSS selector. See the example below for a direct child "li" for a "ul" element:
In Xpath locator
//ul/liIn CSS selector
css=ul > li
(5) Child or Subchild:
A direct child of an element is denoted as "//" in Xpath and a wehite-space(" ") in CSS selector. See the example below for a child/subchild "li" for a "ul" element:
In Xpath locator
//ul//liIn CSS selector
css=ul liNote that "ul li" and "ul > li" are different. If you are confusing please go through this article.
(6) nth Child:
For finding 'nth' child, in Xpath we denote as "[n]" and in CSS we denote as ":nth-of-type(n)". See the below example,
In Xpath locator
- Coffee
- Tea
- Milk
- Soup
- Soft Drinks
//ul[@id='drinks']/li[5]In CSS selector
css=ul#drinks li:nth-of-type(5)Also you can use ":nth-child" but the difference between ":nth-child" and ":nth-of-type(n)" is:
li:nth-child(2)
This means, select an element if It is a paragraph element and the second child of a parent.
li:nth-of-type(2)
This means, select the second paragraph child of a parent. This is less conditional.
See here for more details on difference between the above two.
If we want to select the "fifth li element" (Soft Drinks) in this list, we can use the nth-of-type, which will find the fifth li in the list.
css=ul#drinks li:nth-of-type(5)On the other hand, if we want to get the "fifth element" only if it is a li element, we can use a filtered nth-child which will select again (Soft Drinks) here.
css=ul#drinks li:nth-child(5)(7) Parent of an element:
Parent of an element can be represented as "/.." in Xpath and ":parent" in CSS selectors. For example, if you want to indicate parent of the list item of class 'blue'
- first
- second
- third
- fourth
- fifth
//li[@class='blue']/..In CSS selector
css=li.blue:parent
(8) Next Sibling:
Next sibling is nothing but next adjacent element which is inside the same parent on the page. An adjacent sibling combinator selector allows you to select an element that is directly after another specific element. For example, If you want to select the sibling of "li" element with class "blue" which is 'second' list item,
In Xpath locator
//li[@class='blue']/../li[2]In CSS selector
css=li.blue + liSimilarly, if you want to indicate 'third' list item, see the below
In Xpath locator
//li[@class='blue']/../li[3]In CSS selector
css=li.blue + li + li
(9) Match by Innertext:
There is a javascript methodcontains() which can be used to check the inner text of a web element. For example a link with text "Sign in"
In Xpath locator
//a[contains(text(),'Sign in')]or
//a[contains(string(),'Sign in')]In CSS selector
css=a:contains('Sign in')
(10) Match by Sub-string:
This is interesting and is described below. With this we can match strings with its partial text. E.g. prefix, suffix or any pattern(sub-string)
(i) Match a Sub-string(pattern):The summary of sub-string match is listed out in the following table:
Taking an example of a 'div' with an 'id' that contains the text "pattern"
In Xpath locator, we need to use "contains()" to match a sub-string...
//div[contains(@id,'pattern')]In CSS selector, we need to use "*=" for matching a sub-string
css=div[id*='pattern']
(ii) Match a prefix:
Taking an example of a 'div' with an 'id' that starts with the text "prefixString"
In Xpath locator, we need to use "starts-with" to match a prefix...
//div[starts-with(@id,"prefixString")]In CSS selector, we need to use "^=" for matching a prefix
css=div[id^='prefixString']
(iii) Match a suffix:
Taking an example of a 'div' with an 'id' that starts with the text "suffixString"
In Xpath locator, we need to use "ends-with" to match a suffix Note that "ends-with()" is a standard XPath 2.0 function only, it won't work if you are using Xpath 1.0 engine
//div[ends-with(@id,"suffixString")]In CSS selector, we need to use "$=" for matching a suffix
css=div[id$='suffixString']
Match a Sub-string | Match a Prefix | Match a Suffix | |
---|---|---|---|
Xpath | contains() | starts-with() | ends-with() |
CSS | *= | ^= | $= |
Easy Way To Automate Using WebDriver
WebDriver is a clean, fast framework for Automation development of web-apps.
WebDriver takes many advantages over selenium because selenium is written in
java-script which causes a significant weakness: browsers impose a pretty
strictly model , try to upload a file ,form control etc.
webDriver takes a different approach to solve the same problem as selenium. Rather than being running a java-script application within a browser, it uses whichever the mechanism is most appropriate to control the browser. Like for Firefox ,this means that webDriver is implemented as an extension.
Please download the respective jar related to your language from google code selenium project Download
Now follow below steps:-
1:- Extract the download file into a folder name and include the jars file ion your ClassPath
2:- Sample coding in java
webDriver takes a different approach to solve the same problem as selenium. Rather than being running a java-script application within a browser, it uses whichever the mechanism is most appropriate to control the browser. Like for Firefox ,this means that webDriver is implemented as an extension.
The real beauty which I like most is real time
environment, which means we are more closely modeling how the user interacts
with the browser, and that we can type into "file" input elements. WebDriver can
make use of facilities offered by the Operating System.
Please download the respective jar related to your language from google code selenium project Download
Now follow below steps:-
1:- Extract the download file into a folder name and include the jars file ion your ClassPath
2:- Sample coding in java
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class WebDriverTest{
@Test
public void testGoogleSearch()throws Exception{
WebDriver driver = new FirefoxDriver();
// And now use this to visit Google
driver.get(http://www.google.com/);
// Find the text input element by its name
WebElement element = driver.findElement(By.name("q"));
// Enter something to search for
element.sendKeys("xt global");
// Now submit the form. WebDriver will find the form for us from the element
element.submit();
// Check the title of the page
System.out.println("Page title is: " + driver.getTitle());
driver.close();
}
}
Subscribe to:
Posts (Atom)