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

Selenium Introduction

Selenium is an open source test automation tool that supports testing web applications across different browsers and platforms. It has several components, including Selenium IDE (a simple record and playback tool), Selenium WebDriver (for test automation without a separate server), and Selenium Grid (for distributed testing). Selenium can test functionality and performance across browsers like Chrome, Firefox, IE and Safari. It supports languages like Java, Python, C#, and Ruby and can automate tests for mobile apps as well.

Uploaded by

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

Selenium Introduction

Selenium is an open source test automation tool that supports testing web applications across different browsers and platforms. It has several components, including Selenium IDE (a simple record and playback tool), Selenium WebDriver (for test automation without a separate server), and Selenium Grid (for distributed testing). Selenium can test functionality and performance across browsers like Chrome, Firefox, IE and Safari. It supports languages like Java, Python, C#, and Ruby and can automate tests for mobile apps as well.

Uploaded by

Developer 4
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 64

Selenium Introduction

1. Selenium is a free (open source) automated testing suite for


web applications across different browsers, platforms and
programming languages.
2. Selenium can be easily deployed on platforms such as
Windows, Linux, Solaris and Macintosh. Moreover, it supports
for mobile applications like iOS and android.
3. Languages supported by Selenium include C#, Java, Perl,
PHP, Python and Ruby.
4. Browsers supported by Selenium include Internet Explorer,
Mozilla Firefox, Google Chrome and Safari.
5. Automation testing covers both functional and performance
test on an application.

Selenium Features
1. Selenium is a free (open source) automated testing suite for
web applications across different browsers, platforms and
programming languages.
2. Selenium IDE provides a playback and record feature for
authoring tests without the need to learn a test scripting
language.
3. It helps testers to record their actions and export them as a
reusable script with a simple-to-understand and easy-to-use
interface.
4. It also supports parallel test execution which reduces time and
increases the efficiency of tests.
5. Selenium can be integrated with frameworks like Ant and
Maven for source code compilation, and can be integrated
with testing frameworks like TestNG for application testing and
generating reports.
6. Selenium requires fewer resources as compared to other
automation test tools.
7. Selenium web driver does not require server installation, test
scripts interact directly with the browser.
Selenium Limitations
1. Selenium does not support automation testing for desktop
applications.
2. Selenium requires high skill sets in order to automate tests
more effectively.
3. Since Selenium is open source software, you have to rely on
community forums to get your technical issues resolved.
4. We should know at least one of the supported programming
languages to create tests scripts in Selenium WebDriver.
5. Selenium does not have any inbuilt reportingcapability; you
have to rely on plug-ins like JUnit and TestNG for test reports.
6. It is not possible to perform testing on images.
7. No one is responsible for new features usage; they may or
may not work properly.

Selenium Tool Suite


1. Selenium is not just a single tool but a suite of software's,
each catering to different testing needs of an organization. It
has four components.
o Selenium Integrated Development Environment (IDE)
o Selenium Remote Control (RC) [Now Deprecated]
o WebDriver
o Selenium Grid

Selenium IDE
1. Selenium Integrated Development Environment (IDE) is the
simplest framework in the Selenium suite and is the easiest
one to learn.
2. It is a Firefox/Chrome plugin that you can install as easily as
you can with other plugins.
3. However, because of its simplicity, Selenium IDE should only
be used as a prototyping tool.
4. Selenium IDE is implemented as Firefox extension which
provides record and playback functionality on test scripts.
5. It allows testers to export recorded scripts in many languages
like HTML, Java, Ruby, RSpec, Python, C#, JUnit and
TestNG. You can use these exported script in Selenium RC or
Webdriver.

Selenium IDE-Installation
1. Open Selenium official websiteseleniumhq.org
2. Then click on Download Section.
3. In the webpage search for Selenium IDE and click on Chrome
to install Google Chrome plug-in or click on Firefox to install
Firefox Plug-in.
4. Restart you browser, go to the top right corner on your
browser and look for the Selenium IDE icon.
5. Click on that icon to launch Selenium IDE.

Selenium IDE-Features
1. Very easy to use and install.
2. No programming experience is requied.
3. Export tests to different programming languages.

Selenium IDE-Limitations
1. Available in only Firefox and Chrome.
2. Designed only to create prototypes of tests.
3. Test execution is slow.

Selenium Webdriver
1. Selenium WebDriver is the most important component of
Selenium Tool's Suite.
2. The initial version of Selenium i.e Selenium v1 consisted of
only IDE, RC and Grid. Selenium WebDriver was first
introduced as a part of Selenium v2.0. However, with the
release of Selenium v3, RC has been deprecated and moved
to legacy package.
3. In WebDriver, test scripts can be developed using any of the
supported programming languages and can be run directly in
most modern web browsers. Languages supported by
WebDriver include C#, Java, Perl, PHP, Python and Ruby.
4. Selenium Web driver is most popular with Java and C#.
5. Selenium WebDriver performs much faster as compared to
Selenium RC because it makes direct calls to the web
browsers. RC on the other hand needs an RC server to
interact with the browser.
6. Selenium uses drivers, specific to each browser in order to
establish a secure connection with the browser without
revealing the internal logic of browser's functionality.
7. WebDriver is supporting dynamic web pages where elements
of a page may change without the page itself being reloaded.
8. The more pain while doing automation is the handling
Javascripts alerts & prompts. The WebDriver very verse with
handle the Javascript alerts, prompts and handling multiple
frames, multiple browser windows.

Selenium WebDriver- Features


 Multiple Browser Support
 Multiple Languages Support
 Speed
 Simple Commands

Selenium WebDriver- Installation


 Download and Install Java
 Download and Configure Eclipse IDE
 Download Selenium WebDriver Java Client
 Configure Selenium WebDriver
Selenium WebDriver- First TestCase
 Step:1 Launch Eclipse IDE and create a java project as
"SeleniumClasses". Then create a class under this project.
We will write our first Selenium test script in the
"BrowserDemo" file under the "SeleniumClasses" test suite.
 Step:2 In the second step you have to download driver based
on the browser. For example geckodriver for firefox,
chromedriver for googlechrome, iedriverserver for
internetexplorer. You can download these file from the official
website of selenium.
 Step:3VisitSelenium Official Websiteand then click on
download tab and based on your requirement download any
driver related to your Operating System.
 Step:4 Open class which we are created in step 1 and write
the code which you want to execute.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class BrowserDemo {

public static void main(String[] args) {

//InternetExplorer
System.setProperty("webdriver.ie.driver", "E:\\Softwares\\
IEDriverServer.exe");
WebDriver driver = new InternetExplorerDriver();
driver.manage().window().maximize();
driver.get("http://google.com");
System.out.println(driver.getTitle());
System.out.println(driver.getCurrentUrl());

//GoogleChrome
System.setProperty("webdriver.chrome.driver", "E:\\
Softwares\\ChromeDriver.exe");
WebDriver driver2 = new ChromeDriver();
driver2.manage().window().maximize();
driver2.get("http://google.com");
System.out.println(driver2.getTitle());
System.out.println(driver2.getCurrentUrl());

//Firefox
System.setProperty("webdriver.gecko.driver", "E:\\Softwares\\
geckodriver.exe");
WebDriver driver3 = new InternetExplorerDriver();
driver.manage().window().maximize();
driver3.get("http://google.com");
System.out.println(driver3.getTitle());
System.out.println(driver3.getCurrentUrl());
}
}

1. In selenium, we
use System.setProperty("name","value") method because
the browser doesn’t have a built-in server to run the
automation code so you will need a
Chrome/IE/Gecko(according to requirement) driver server for
communicating your Selenium code to the browser. In this
method we have to pass two parameters, first parameter is
name of the browser which we want to connect and second
parameter is the path of the related driver which we have
downloaded in Step 3.
For example System.setProperty("webdriver.ie.driver",
"E:\\Softwares\\SeleniumDrivers\\IEDriverServer.exe");
2. In the next step we have created a browser object to access
and to perform some operations on that
browser. WebDriver defines common methods which all
browser classes (such as Firefox, Chrome etc.,) use. All these
class methods are derived from WebDriver interface.
For example WebDriver driver = new
InternetExplorerDriver();
3. The WebDriver provides the window interface for setting up
the browser window size, state, and so on. When we call
the maximize() method, the browser window will be
maximized from normal or minimized state.
For example driver.manage().window().maximize();
4. If we want to open a specific URL on that browser we will
use get() method. In that method we have to pass the specific
URL.
For example driver.get("http://google.com");
5. If we want to get current page title we wil
use driver.gettitle() method and if we want to get current
page URL we will use driver.getCurrentUrl() method.

Locating Web Elements


 It is an address that identifies a web element ( say Text Box,
Buttons, Check Boxes etc) uniquely with in the web page.
 Identification of correct elements is a prerequisite to creating
an automation script. But accurate identification of elements is
more difficult than it sounds.
 We have 8 element Locators to recognise Web Elements. The
choice of locator depends largely on your Application Under
Test. Those are:

1. By Id: Locates element using id attribute of the web element.

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

2. By className: Locates the web element using className


attribute.

WebElement element =
driver.findElement(By.className("elementsClass"));

3. By tagName: Locates the web element using its html tag like


div, a, input etc.

WebElement element = driver.findElement(By.tagName("a"));

4. By name: Locates the web element using name attribute.

WebElement element = driver.findElement(By.name("male"));

5. By linkText: Locates the web element of link type using their


text.

WebElement element = driver.findElement(By.linkText("Click


Here"));

6. By partialLinkText: Locates the web element of link type with


partial matching of text.

WebElement element =
driver.findElement(By.partialLinkText("Click"));

7. By cssSelector: Locates the web element using css its CSS


Selector patterns

WebElement element =
driver.findElement(By.cssSelector("div#elementId"));

8. By xpath: Locates the web element using its XPaths


WebElement element =
driver.findElement(By.xpath("//div[@id=’elementId’]"));

 we prefer using id because id of elements are generally


unique. But there can be scenarios where we might not have
id attributes of web elements, also other locators like name,
className might not fetch the unique required web element.
In those scenarios, we should
use cssSelector and xpath locators.
 The sendKeys() method is used to enter the specified value
in the textbox.

driver.findElement(By.cssSelector("div#elementId")).sendKe
ys(“TestSelenium “);

 Click() method is used to click on the web element present on


the web page.

driver.findElement(By.linkText("Click Here")).click();

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

class LocatorsDemo {
public static void main(String[] args) {

System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\
chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://fb.com");

driver.findElement(By.id("email")).sendKeys("9052938526");
driver.findElement(By.name("pass")).sendKeys("password");

driver.findElement(By.className("inputtext")).sendKeys("abhishek
@gmail.com");

driver.findElement(By.tagName("input")).sendKeys("7569645388");
driver.findElement(By.partialLinkText("Forgotten")).click();
driver.findElement(By.linkText("Forgotten Password?")).click();

driver.findElement(By.cssSelector("#u_0_q")).sendKeys("90529385
26");

driver.findElement(By.xpath("//*[@id=\"reg_pages_msg\"]/a")).click()
;
}
}

Selenium WebDriver Commands


1. Here we will learn some of the basic selenium commands for
performing operations like opening a URL, clicking on buttons,
writing in textbox, closing the browser etc.

Browser Commands
 get() method: The driver.get() method is used to navigate to a
web page by passing the string URL as parameter.

driver.get("http://facebook.com");

 getTitle() method: In WebDriver, this method fetches the title


of the current web page.

System.out.println(driver.getTitle());
 getCurrentUrl() method: In WebDriver, this method fetches
the string representing the Current URL of the current web
page.

System.out.println(driver.getCurrentUrl());

 close() method: The driver.close() command is used to close


the browser having focus.

driver.close();

 quit() method: The driver.quit command is used to close all


the browser instances open.

driver.quit();

Navigation Commands
 navigate().to() method: The driver.navigate().to() method
does the task of opening a web page like driver.get() method.

driver.navigate().to("http://youtube.com");

 navigate().back() method: Selenium provides


navigate().back() command to move backwards in the
browser's history.

driver.navigate().back();

 navigate().forward() method: Selenium provides


navigate().forward() command to move forward in a browser.

driver.navigate().forward();

 navigate().refresh() method: It is used to refresh a page in


Selenium WebDriver.

driver.navigate().refresh();

 sendKeys(Keys.F5) method: It is used to refresh a page in


Selenium WebDriver on any textbox on the webpage

driver.findElement(By.id("id123")).sendKeys(Keys.F5);
WebElement Commands
 click() method: The click() method in Selenium is used to
perform the click operation on web elements.

driver.findElement(By.id("button1")).click();

 sendKeys() method: The sendKeys() method can be used


for writing in a textbox or any element of text input type.

driver.findElement(By.id("firstname")).sendKeys("Abhishek");

 clear() method: The clear() method can be used to clear the


text written in a textbox or any web element of text input type.

driver.findElement(By.name("surname")).clear();

 getText() method: In automation, many a times we need to


fetch the text written over a web element for performing some
assertions or debugging. For this, we have getText() method
in selenium webDriver.

driver.findElement(By.id("email")).getText();

 isDisplayed() method: If the element is displayed it will return


TRUE otherwise it will return FALSE.

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

 isEnabled() method: It is used to test whether the element is


enabled to perform some action or not.

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

 isSelected() method: It will display TRUE if the element is


selected otherwise it will print FALSE.

driver.findElement(By.id("Sex-Male")).isSelected();

 submit() method: It will submit the webpage to the server.

driver.findElement(By.id("SubmitButton")).submit();
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

class Selenium {
public static void main(String[] args) throws InterruptedException
{

System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\
chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();

driver.get("file:///C:/Users/user/Desktop/Selenium.html");
System.out.println(driver.getTitle());
System.out.println(driver.getCurrentUrl());
driver.findElement(By.xpath("xpath1"));
driver.close();
driver.quit();
driver.navigate().to("https://google.com");
Thread.sleep(10000);
driver.navigate().back();
Thread.sleep(5000);
driver.navigate().forward();
driver.navigate().refresh();

driver.findElement(By.xpath("hello")).sendKeys("9052938526");
Thread.sleep(5000);
driver.findElement(By.xpath("hello")).clear();

System.out.println(driver.findElement(By.id("heading2")).getText());

System.out.println(driver.findElement(By.id("selenium")).isDisplayed
());

System.out.println(driver.findElement(By.id("b2")).isEnabled());

System.out.println(driver.findElement(By.id("male")).isSelected());
}

Handling Textboxes in Selenium


1. Basically a textbox is an input tag and will accept character
sequence.
2. Input boxes refer to either of these two types:
o Text Fields- text boxes that accept typed values and
show them as they are.
o Password Fields- text boxes that accept typed values but
mask them as a series of special characters (commonly
dots and asterisks) to avoid sensitive values to be
displayed.
3. We need to use sendKeys() method to enter data into textbox
after identifying the webelement on the webpage.

driver.findElement(By.id("name")).sendKeys("Abhishek");

4. To clear the textbox we can use clear() method of selenium.


driver.findElement(By.id("name")).clear();

5. We can retrieve value which we have typed or already typed


in text box. It will be useful when we want to verify if correct
value is typed or to know existing value in text box. To retrieve
value from text box, we need to
use getAttribute("value") method.

driver.findElement(By.id("name")).getAttribute("value");

6. We can also get the type of the text box. For this purpose we
use getAttribute("type") method.

driver.findElement(By.id("name")).getAttribute("type");

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

class Selenium {
public static void main(String[] args) throws InterruptedException
{

System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\
chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();

driver.get("file:///C:/Users/user/Desktop/Selenium.html");
WebElement name = driver.findElement(By.id("name"));
name.sendKeys("Kotha Abhishek");
driver.findElement(By.id("pwd")).sendKeys("Abhishek");
name.clear();
System.out.println(name.getAttribute("value"));
System.out.println(name.getAttribute("type"));

Handling Alerts / PopUps in Selenium


1. Alert is a small message box which displays on-screen
notification to give the user some kind of information or ask for
permission to perform certain kind of operation. It may be also
used for warning purpose.
2. Selenium WebDriver provides three methods to accept and
reject the Alert depending on the Alert types.
3. We need to use accept() to click on the 'Ok' button of the
alert.

driver.switchTo().alert().accept();

4. We can use dismiss() to click on the 'Cancel' button of the


alert.

driver.switchTo().alert().dismiss();

5. We need to use getText() to capture the alert message.

driver.switchTo().alert().getText();

6. We can use sendKeys("Text") to send some data to the alert


box.
driver.switchTo().alert().sendKeys("Text");

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

class Selenium {
public static void main(String[] args) throws InterruptedException
{

System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\
chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();

driver.get("file:///C:/Users/user/Desktop/Selenium.html");
driver.findElement(By.id("file")).click();
driver.findElement(By.id("file")).sendKeys("C:\\Users\\user\\
Desktop\\Selenium.html");
Thread.sleep(3000);
driver.switchTo().alert().accept();
driver.switchTo().alert().dismiss();
System.out.println(driver.switchTo().alert().getText());
driver.switchTo().alert().sendKeys("9052938526");
driver.switchTo().alert().accept();

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


alertbox.sendKeys("9052938526");
alertbox.accept();

Handling Dropdown in Selenium


1. The 'Select' class in Selenium WebDriver is used for selecting
an option in a dropdown. The objects of Select type can be
initialized by passing the dropdown webElement as parameter
to its constructor.
2. To perform any action, the first task is to identify the element
group. I am saying it a group, as DropDown /Multiple Select is
not a single element. They always have a single name but and
they contain one or more than one element in them.

Select dropdown = new


Select(driver.findElement(By.name("country")));

3. WebDriver provides three ways to select an option from the


drop-down menu.
4. We can use selectByIndex() to select an option based on its
index, beginning with 0.

dropdown.selectByIndex(5);

5. We need to use selectByValue() to select an option based on


its 'value' attribute.

dropdown.selectByValue("India");

6. We can use selectByVisibleText() to select an option based


on the text over the option.
dropdown.selectByVisibleText("Database Testing");

7. We can use getOptions( ) to get the all options belonging to


the Select tag. It takes no parameter and returns
List<WebElements>.

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


int size=options.size();
System.out.println(size);
for(int i =0; i<size ; i++){
String optValue = options.get(i).getText();
System.out.println(optValue);
}

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;

class Selenium {
public static void main(String[] args) {

System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\
chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();

driver.get("file:///C:/Users/user/Desktop/Selenium.html");
Select dropdown1 = new
Select(driver.findElement(By.name("country")));
dropdown1.selectByVisibleText("India");
dropdown1.selectByIndex(5);
dropdown1.selectByValue("Australia");
List<WebElement> list1 = dropdown1.getOptions();
int size=list1.size();
System.out.println(size);
for(int i =0; i<size ; i++){
String optValue = list1.get(i).getText();
System.out.println(optValue);
}
}
}

Handling Tables in Selenium


1. There are two types of HTML tables published on the web.
o Static tables : Data is static i.e. Number of rows and
columns are fixed.
o Dynamic tables : Data is dynamic i.e. Number of rows
and columns are NOT fixed.
2. Handling static table is easy, but dynamic table is a little bit
difficult as rows and columns are not constant.
3. Below tags are generally defined in html tables :
o ’table’ tag defines HTML table.
o ’tbody’ tag defines a container for rows and columns.
o ’tr’ defines rows in an HTML table.
o ’td’/’th’ define the column of an HTML table.
4. First get the entire HTML table and store this in a variable of
type web element.

WebElement
htmltable=driver.findElement(By.xpath("//*[@id='main']/table[1]
/tbody"));

5. Get all the rows with tag name ‘tr’ and store all the elements in
a list of web elements. Now all the elements with tag ‘tr’ are
stored in ‘rows’ list.

List<WebElement>
rows=htmltable.findElements(By.tagName("tr"));

6. Loop through each row and get the list of elements with tag
‘th’.

List<WebElement>
columns=rows.get(rnum).findElements(By.tagName("th"));
System.out.println("Number of columns:"+columns.size());

7. Iterate using ‘columns.getsize()’ and get the details of each


cell.

System.out.println(columns.get(cnum).getText());

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

class Selenium {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\
chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();

driver.get("file:///C:/Users/user/Desktop/Selenium.html");
WebElement table =
driver.findElement(By.xpath("/html/body/table"));
List <WebElement> rows =
table.findElements(By.xpath("/html/body/table/tbody/tr"));
int rowcount = rows.size();

List <WebElement> columns =


table.findElements(By.xpath("/html/body/table/tbody/tr[1]/th"));
int columncount = columns.size();

List <WebElement> cells =


table.findElements(By.xpath("/html/body/table/tbody/tr/th"));
System.out.println(cells.size());

for(int i=1; i<=1; i++){


for(int j=1; j<=columncount; j++) {

System.out.print(table.findElement(By.xpath("/html/body/table/tbody
/tr["+i+"]/th["+j+"]")).getText()+" ");
}
System.out.println();
}
for(int i=2; i<=rowcount; i++){
for(int j=1; j<=columncount; j++) {

System.out.print(table.findElement(By.xpath("/html/body/table/tbody
/tr["+i+"]/td["+j+"]")).getText()+" ");
}
System.out.println();
}
}
}

Handling iFrames in Selenium


1. IFrame is a web page which is embedded in another web
page or an HTML document embedded inside another HTML
document.
2. The IFrame is often used to insert content from another
source, such as an advertisement, into a Web page.
3. We cannot detect the frames by just seeing the page or by
inspecting.
4. We can identify the iframes using methods given below:
o Right click on the element, If you find the option like 'This
Frame', 'view Frame source' or ''Reload Frame' then it is
an iframe.
o Right click on the page and click 'View Page Source' and
Search with the 'iframe', if you can find any tag name
with the 'iframe' then it is meaning to say the page
consisting an iframe.
5. We can even identify total number of iframes by using below
snippet.

int size = driver.findElements(By.tagName("iframe")).size();


6. Basically, we can switch over the elements in frames using 2
ways.
7. Switch to the frame by index : Index is one of the attributes
for the Iframe through which we can switch to it. Index of the
iframe starts with '0'.

driver.switchTo().frame(0);

8. Switch to the frame by Name or ID : Name and ID are


attributes of iframe through which we can switch to the frame.

driver.switchTo().frame("iframe1");

9. Switch back to the Main Frame : To move back to the parent
frame, you can either use switchTo().parentFrame() or if you
want to get back to the main (or most parent) frame, you can
use switchTo().defaultContent();

driver.switchTo().parentFrame();
driver.switchTo().defaultContent();

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

class Selenium {
public static void main(String[] args) {

System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\
chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("file:///C:/Users/user/Desktop/Selenium.html");
driver.switchTo().frame("seleniumframe");
String heading =
driver.findElement(By.xpath("//*[@id=\"1\"]")).getText();
System.out.println(heading);

driver.switchTo().parentFrame();

driver.switchTo().frame(1);
String heading2 =
driver.findElement(By.xpath("//*[@id=\"1\"]")).getText();
System.out.println(heading2);

int framecount =
driver.findElements(By.tagName("iframe")).size();
System.out.println(framecount);

}
}

Selenium Headless Browser Testing


1. A headless browser is a web-browser without a graphical user
interface. This program will behave just like a browser but will
not show any GUI.
2. Improves speed and performance.
3. Helps you multitask.
4. Some of the examples of Headless Drivers include :
o HtmlUnit
o Chrome
o Firefox
5. HTMLUnitDriver : HTML UnitDriver is the most light weight
and fastest implementation headless browser for of
WebDriver. It is based on HtmlUnit. It is known as Headless
Browser Driver. It is same as Chrome, IE, or FireFox driver,
but it does not have GUI so one cannot see the test execution
on screen.
o Support for the HTTPS and HTTP protocols
o Support for HTML responses ( clicking links, submitting
forms, walking the DOM model of the HTML document
etc.)
o Support for cookies
o Excellent JavaScript support
o Support for submit methods GET and POST

WebDriver driver = new HtmlUnitDriver();

We have to download 2 jar files ( htmlunit-driver-2.41.0-jar-


with-dependencies.jar , htmlunit-driver-2.41.0.jar ) for HtmlUnit
Driver and we have to bind them with our project to use
HtmlUnitDriver.Click here to download files

6. Chrome Driver : Chrome provides a headless mode, which


works well overall. The biggest downside is that you need to
be able to install Chrome. You don’t need a UI, but installing
software is not always possible.

ChromeOptions options = new ChromeOptions();


options.addArguments("--headless");
(or)
options.setHeadless(true);
WebDriver driver = new ChromeDriver(options);
7. Gecko Driver : Firefox also has a headless mode. which
works just like the Chrome one. You download the Gecko
Driver and use selenium-firefox-driver.

FirefoxBinary firefoxBinary = new FirefoxBinary();


firefoxBinary.addCommandLineOptions("--headless");
FirefoxOptions options = new FirefoxOptions();
options.setBinary(firefoxBinary);

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;

class Selenium {
public static void main(String[] args) {

System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\
chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("headless");
// options.setHeadless(true);
WebDriver driver = new ChromeDriver(options);

WebDriver driver = new HtmlUnitDriver();

FirefoxBinary firefoxBinary = new FirefoxBinary();


firefoxBinary.addCommandLineOptions("--headless");
FirefoxOptions options = new FirefoxOptions();
options.setBinary(firefoxBinary);
WebDriver driver = new FirefoxDriver(options);

driver.get("file:///C:/Users/user/Desktop/Selenium.html");

System.out.println(driver.getCurrentUrl());
System.out.println(driver.getTitle());

}
}

Verify If Options In Dropdown Are Sorted or


Not?
1. Open the browser and navigate to the webpage.
2. Find the dropdown using the findElement method in selenium.
Create a object to Select class and pass the dropdown
element as the parameter to constructor.
3. Using getOptions() method from Select class you can get all
the options from the dropdown in the form of WebElement.
Using the loop we can retrive the values from the List of
WebElement.
4. Now lets create a temporary list called tempList and get the
values from originalList. Now sort the Either tempList or
originalList and compare them, We can sort the list using the
Collections.sort(list) method.
5. We can compare the list using conditional statement.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;

class Selenium {
public static void main(String[] args) throws InterruptedException{

System.setProperty("webdriver.chrome.driver","E:\\Drivers\\
chromedriver.exe");
WebDriver driver= new ChromeDriver();

driver.get("file:///C:/Users/user/Desktop/Selenium.html");

WebElement carslist = driver.findElement(By.id("cars"));


Select dropdown = new Select(carslist);

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

List options = new ArrayList();


for(WebElement optionElement : allOptions){
options.add(optionElement.getText());
}

System.out.println("Options in dropdown with Default


order :"+options);

List tempList = new ArrayList<>(options);

Collections.sort(tempList);

System.out.println("Sorted List "+ tempList);

boolean ifSortedAscending = options.equals(tempList);

if(ifSortedAscending)
{
System.out.println("List is sorted");
}
else
System.out.println("List is not sorted.");

driver.quit();

}
}
Handle Multiple Windows/Tabs in Selenium
1. On an HTML page, a link can open up in a new window/tab.
2. There is only one way you can get multiple windows via
Selenium web driver, that is by clicking on a link that opens
the page in a new browser window.
3. Selenium web driver keeps a track of how many windows it
opened during a session.
4. Window handle is a unique string value that uniquely identifies
a Browser window on desktop. It is guaranteed that each
browser will have a unique window handle.
5. To get Window handle WebDriver interface provides two
methods – getWindowHandle(), getWindowHandles().
6. getWindowHandle() : method return a string value and it
returns the Window handle of current focused browser
window.
7. getWindowHandles() : method returns a set of all Window
handles of all the browsers that were opened in the session.
8. There is a concept of current focused window which means
that all selenium webdriver commands will go to the focused
window. By default the focus is always on the Parent window.
9. WebDriver.SwitchTo().window(String
windowHandle) : This command takes in a window handle
and switches the driver context on that window. Once the
Switch happens all the driver commands will go to the newly
focused window. This is very important to understand, without
switching to the desired window we wil not be able to perform
any action on that window.
10. WebDriver.Close() : command will close the current
window on which the focus is present. This can be used to
close windows selectively. Just switch to the window that you
want to close by using the correct Window handle and the call
the WebDriver.close command.
11. WebDriver.quit() : command will close all the windows
opened in the session. This command basically shuts down
the driver instance and any further commands to WebDriver
results in exception.

import java.util.Iterator;
import java.util.Set;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

class Selenium {
public static void main(String[] args) {

System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\
chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();

driver.get("file:///C:/Users/user/Desktop/Selenium.html");

driver.findElement(By.xpath("//*[@id=\'c\']")).click();
driver.findElement(By.xpath("//*[@id=\'java\']")).click();
driver.findElement(By.xpath("//*[@id=\'python\']")).click();

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


int size = windows.size();
System.out.println(windows);
String ids[] = new String[size];

Iterator<String> itr = windows.iterator();

for(int i=0; i<size; i++) {


ids[i] = itr.next();
}

System.out.println("Parent window Title : "+driver.getTitle());

driver.switchTo().window(ids[2]);
System.out.println("2nd Child window Title : "+driver.getTitle());

driver.switchTo().window(ids[3]);
System.out.println("3rd Child window Title : "+driver.getTitle());

driver.switchTo().window(ids[1]);
System.out.println("1st Child window Title : "+driver.getTitle());

driver.switchTo().window(ids[0]);
System.out.println("Parent window Title : "+driver.getTitle());
driver.quit();

}
}
Mouse Click & Keyboard Event: Actions
Class
1. Actions class is an ability provided by Selenium for handling
keyboard and mouse events.
2. In Selenium WebDriver, handling these events includes
operations such as drag and drop, clicking on multiple
elements with the control key.
3. The following are the most commonly used keyboard and
mouse events provided by the Actions class.
4. clickAndHold() : Clicks (without releasing) at the current
mouse location.
5. contextClick() : Performs a context-click at the current mouse
locationPerforms a key release.. (Right Click Mouse Action).
6. doubleClick() : Performs a double-click at the current mouse
location.
7. dragAndDrop(source, target) : Performs click-and-hold at
the location of the source element, moves to the location of
the target element, then releases the mouse.
8. keyDown(modifier_key) : Performs a modifier key press.
Does not release the modifier key - subsequent interactions
may assume it's kept pressed. (Keys.ALT, Keys.SHIFT, or
Keys.CONTROL).
9. keyUp(modifier _key) : Performs a key release.
10. moveToElement(toElement) : Moves the mouse to the
middle of the element.
11. release() : Releases the depressed left mouse button at
the current mouse location.
12. Instantiate a new Actions object.

Actions action = new Actions(driver);

13. Use the perform() method when executing the Action


object
14. You can build a series of actions using the Action and
Actions classes. Just remember to close the series with
the build() method.
15. Build().perform() is used to compile and execute the
actions class.

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

class Selenium {
public static void main(String[] args) throws InterruptedException
{

System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\
chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();

driver.get("file:///C:/Users/user/Desktop/Selenium.html");

Actions act = new Actions(driver);

WebElement source =
driver.findElement(By.xpath("//*[@id=\'box6\']"));
WebElement destination =
driver.findElement(By.xpath("//*[@id=\'box106\']"));
WebElement element3 =
driver.findElement(By.xpath("//*[@id=\'header\']/nav/div/div[2]/ul/
li[6]/ul/li[1]/ul/li[2]/a"));

act.moveToElement(element1).build().perform();
act.moveToElement(element2).build().perform();
act.moveToElement(element3).click().build().perform();

act.moveToElement(element1).moveToElement(element2).moveTo
Element(element3).click().build().perform();

act.clickAndHold(source).moveToElement(destination).release().bui
ld().perform();

WebElement source2 =
driver.findElement(By.xpath("//*[@id=\'box1\']"));
WebElement destination2 =
driver.findElement(By.xpath("//*[@id=\'box101\']"));

act.dragAndDrop(source, destination).build().perform();

act.clickAndHold(source2).moveToElement(destination2).release().
build().perform();

Thread.sleep(5000);
WebElement button =
driver.findElement(By.xpath("/html/body/div/section/div/div/div/p/
span"));
act.contextClick(button).build().perform();

act.moveToElement(driver.findElement(By.xpath("/html/body/ul/li[5]/
span"))).click().build().perform();

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


act.keyDown(name,
Keys.SHIFT).sendKeys("abhishek").build().perform();

}
}

How to Find All Broken links using Selenium


1. Broken links are links or URLs that are not reachable. They
may be down or not functioning due to some server error.
2. You should always make sure that there are no broken links
on the site because the user should not land into an error
page.
3. Manual checking of links is a tedious task, because each
webpage may have a large number of links & manual process
has to be repeated for all pages.
4. Collect all the links in the web page based on <a> tag.
5. Send HTTP request for the link and read HTTP
response code.
6. Find out whether the link is valid or broken based on HTTP
response code.
7. Repeat this for all the links captured.
8. There are different HTTP status codes which are having
different purposes.
9. An URL will always have a status with 2xx which is valid.
10. For an invalid request, HTTP status is 4xx and 5xx.
11. 4xx class of status code is mainly for client side error,
and 5xx class of status codes is mainly for the server
response error.
12. We will most likely be unable to confirm if that link is
working or not until we click and confirm it.
13. Identify all links in a webpage and store them in List.

List<WebElement> links =
driver.findElements(By.tagName("a"));

14. Obtain Iterator to traverse through the List.

Iterator it = links.iterator();

15. Now the most important part is to check in the links are
working. Here I will introduce to you a Class from Java,
called HttpURLConnection class. This class is used to make
HTTP requests to the webserver hosting the links extracted
16. Consider an air ticket booking application. The color of
booked and available seats are different. Red represents the
booked seats, and available seats are represented by green.
So, for verifying whether a seat is booked or available, QAs
need to fetch the attribute (color) value through the test script.
Once the status of the seat is verified, only then can QAs
verify further test scenarios.

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

class Selenium {
public static void main(String[] args) throws InterruptedException,
IOException {

System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\
chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();

driver.get("http://newtours.demoaut.com/");

List<WebElement> links =
driver.findElements(By.tagName("a"));

System.out.println(links.size());

for(int i=0; i<links.size(); i++) {


WebElement element = links.get(i);
String url = element.getAttribute("href");

URL link=new URL(url);


HttpURLConnection httpcon = (HttpURLConnection)
link.openConnection();
httpcon.connect();

int rescode = httpcon.getResponseCode();

if(rescode>=400) {
System.out.println(url + "---> is broken link");
}else {
System.out.println(url + "---> is valid link");
}
}
}
}

Download Different Files in Chrome and


FireFox

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.firefox.FirefoxProfile;

class Selenium {
public static void main(String[] args) {

System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\
chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();

driver.get("http://demo.automationtesting.in/FileDownload.html");

driver.findElement(By.xpath("//*[@id=\"textbox\"]")).sendKeys("Testi
ng text file");
driver.findElement(By.xpath("//*[@id=\"createTxt\"]")).click();
driver.findElement(By.xpath("//*[@id=\"link-to-
download\"]")).click();

FirefoxProfile profile = new FirefoxProfile();

profile.setPreference("browser.helperApps.neverAsk.saveToDisk",
"application/pdf");

profile.setPreference("browser.download.manager.showWhenStarti
ng", false);
profile.setPreference("pdfjs.disabled", true);

FirefoxOptions option = new FirefoxOptions();


option.setProfile(profile);

System.setProperty("webdriver.gecko.driver", "E:\\Drivers\\
geckodriver.exe");
WebDriver driver = new FirefoxDriver(option);
driver.manage().window().maximize();

driver.get("http://demo.automationtesting.in/FileDownload.html");

driver.findElement(By.xpath("//*[@id=\"textbox\"]")).sendKeys("Testi
ng text file");
driver.findElement(By.xpath("//*[@id=\"createTxt\"]")).click();
driver.findElement(By.xpath("//*[@id=\"link-to-
download\"]")).click();

}
}

Create Your Own Dynamic XPATH in


selenium

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.firefox.FirefoxProfile;

class Selenium {
public static void main(String[] args) {

System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\
chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();

driver.get("file:///C:/Users/user/Desktop/Selenium.html");

//
driver.findElement(By.xpath("//input[@type='text']")).sendKeys("Abh
ishek");
//
driver.findElement(By.xpath("//input[@placeholder='Name']")).send
Keys("Abhishek");

// driver.findElement(By.xpath("//button[text()='Login with
Google']")).click();

//driver.findElement(By.xpath("button[contains(text(),'kjasg')]")).click
();
//driver.findElement(By.xpath("button[starts-
with(text(),'kjasg')]")).click();
//driver.findElement(By.xpath("button[ends-
with(text(),'kjasg')]")).click();

//input[@id='login']/following-sibling::button
//input[@id='login']/preceding-sibling::button

//input[@id='login']/parent::form

//input[@type='text' and @placeholder='surname']


}
}

Upload Files Using sikuli in selenium

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.sikuli.script.FindFailed;
import org.sikuli.script.Pattern;
import org.sikuli.script.Screen;

class Selenium {
public static void main(String[] args) throws FindFailed {

System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\
chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("file:///C:/Users/user/Desktop/Selenium.html");

Actions act = new Actions(driver);

act.click(driver.findElement(By.xpath("//*[@id=\'file\']"))).build().perfo
rm();

Pattern p1 = new Pattern("C:\\Users\\user\\Desktop\\


ImageRecog\\textbox.PNG");
Pattern p2 = new Pattern("C:\\Users\\user\\Desktop\\
ImageRecog\\openbotton.PNG");

Screen sc = new Screen();

sc.type(p1, "E:\\Abhishek Project\\Base Paper final.pdf");


sc.click(p2);
}
}

Handle Video Controls Using sikuli in


selenium

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.sikuli.script.FindFailed;
import org.sikuli.script.Pattern;
import org.sikuli.script.Screen;

class Selenium {
public static void main(String[] args) throws FindFailed {

System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\
chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();

driver.get("file:///C:/Users/user/Desktop/Selenium.html");

Pattern p1 = new Pattern("C:\\Users\\user\\Desktop\\Sikuli\\


play.PNG");
Pattern p2 = new Pattern("C:\\Users\\user\\Desktop\\Sikuli\\
mute.PNG");
Pattern p3 = new Pattern("C:\\Users\\user\\Desktop\\Sikuli\\
maximize.PNG");

Screen sc = new Screen();

sc.click(p1);
sc.click(p2);
sc.click(p3);

}
}
Read Data from MS-Excel in selenium

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

class Selenium {
public static void main(String[] args) throws IOException {

// System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\
chromedriver.exe");
// WebDriver driver = new ChromeDriver();
// driver.manage().window().maximize();
// driver.get("file:///C:/Users/user/Desktop/Selenium.html");

FileInputStream file = new FileInputStream("C:\\Users\\user\\


Desktop\\EmpInfo.xlsx");

XSSFWorkbook wb = new XSSFWorkbook(file);

XSSFSheet s = wb.getSheetAt(0);

int row = s.getLastRowNum();


int column = s.getRow(0).getLastCellNum();

for(int i=0; i<=row; i++) { // read to use each row


XSSFRow currentrow = s.getRow(i);

for(int j=0; j<column; j++) { // read to use each cell on


current row
String value = currentrow.getCell(j).toString();
System.out.print(value+" ");
}
System.out.println();
}

}
}

Read Data from Excel in selenium

import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

class Selenium {
public static void main(String[] args) throws IOException {

System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\
chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://localhost:8084/KothaAbhishekProject/");

FileInputStream file = new FileInputStream("C:\\Users\\user\\


Desktop\\EmpInfo.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheet("Sheet3");

int rowcount = sheet.getLastRowNum();

for(int i=1; i<=rowcount; i++) {


XSSFRow row = sheet.getRow(i);

String cell1 = row.getCell(0).getStringCellValue();


String cell2 = row.getCell(1).getStringCellValue();
String cell3 = row.getCell(2).getStringCellValue();
int cell4 = (int)row.getCell(3).getNumericCellValue();
String cell5 = row.getCell(4).getStringCellValue();

driver.findElement(By.xpath("//input[@name='name']")).sendKeys(c
ell1);

driver.findElement(By.xpath("//input[@name='pwd']")).sendKeys(cel
l2);

driver.findElement(By.xpath("//input[@name='email']")).sendKeys(c
ell3);

driver.findElement(By.xpath("//input[@name='number']")).sendKeys
(String.valueOf(cell4));
//

driver.findElement(By.xpath("//input[@name='gender']")).sendKeys(
cell5).click();

List radiobutton = driver.findElements(By.name("gender"));


int size = radiobutton.size();

for(int j=0; j<size; j++) {


String val = radiobutton.get(j).getAttribute("value");

if(val.equalsIgnoreCase(cell5)) {
radiobutton.get(j).click();
break;
}

}
driver.findElement(By.xpath("//input[@name='Register']")).click();

driver.get("http://localhost:8084/KothaAbhishekProject/");

}
driver.close();

workbook.close();

}
}

Write Data into Excel in selenium

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
class Selenium {
public static void main(String[] args) throws IOException{

System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\
chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://localhost:8084/PracticeApplication/");

FileInputStream file = new FileInputStream("C:\\Users\\user\\


Desktop\\EmpInfo.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheet("Sheet4");

int rowcount = sheet.getLastRowNum();

for(int i=1; i<=rowcount; i++) {

XSSFRow row = sheet.getRow(i);

String uname = row.getCell(0).getStringCellValue();


String upassword = row.getCell(1).getStringCellValue();

driver.findElement(By.xpath("//input[@name='name']")).sendKeys(u
name);
driver.findElement(By.xpath("//input[@name='pwd']")).sendKeys(up
assword);

driver.findElement(By.xpath("//input[@name='Login']")).click();

String message=
driver.findElement(By.xpath("//span[@class='error']")).getText();

if(message.equalsIgnoreCase("Valid User")) {
sheet.getRow(i).createCell(2).setCellValue("Pass");
}else {
sheet.getRow(i).createCell(2).setCellValue("Fail");
}

FileOutputStream fout = new FileOutputStream("C:\\Users\\


user\\Desktop\\EmpInfo.xlsx");

workbook.write(fout);

driver.get("http://localhost:8084/PracticeApplication/");
}

workbook.close();
}
}

Robot class in selenium


import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

class Selenium {
public static void main(String[] args) throws AWTException,
InterruptedException{

System.setProperty("webdriver.gecko.driver", "E:\\Drivers\\
geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://demo.automationtesting.in/FileDownload.html");

driver.findElement(By.xpath("//*[@id=\"textbox\"]")).sendKeys("Koth
a Abhishek");
driver.findElement(By.xpath("//*[@id=\"createTxt\"]")).click();
driver.findElement(By.xpath("//*[@id=\"link-to-
download\"]")).click();

Robot robot = new Robot();


Thread.sleep(3000);
robot.keyPress(KeyEvent.VK_DOWN);
Thread.sleep(3000);
robot.keyPress(KeyEvent.VK_TAB);
Thread.sleep(3000);
robot.keyPress(KeyEvent.VK_TAB);
Thread.sleep(3000);
robot.keyPress(KeyEvent.VK_TAB);
Thread.sleep(3000);
robot.keyPress(KeyEvent.VK_ENTER);

}
}

Upload or Download using Robot Class in


selenium

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
class Selenium {
public static void main(String[] args) throws AWTException {

System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\
chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("file:///C:/Users/user/Desktop/Selenium.html");

Actions act = new Actions(driver);

act.click(driver.findElement(By.xpath("//*[@id=\"upload\"]"))).build().
perform();

Robot robot = new Robot();

StringSelection select = new StringSelection("C:\\Users\\user\\


Desktop\\Abhishek.jpg");

Toolkit.getDefaultToolkit().getSystemClipboard().setContents(select
, null); //ctrl+c

robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V); //ctrl+v
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_V);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
}
}

Calendar or Date Picker in selenium

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

class Selenium {
public static void main(String[] args) throws InterruptedException {

System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\
chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://jqueryui.com/datepicker/");

String date = "32-December-2020";


String arr[] = date.split("-"); // index 0

driver.switchTo().frame(0); // frame swift

driver.findElement(By.xpath("//*[@id=\'datepicker\']")).click();
String month = driver.findElement(By.xpath("//*[@id=\'ui-
datepicker-div\']/div/div/span[1]")).getText();
String year = driver.findElement(By.xpath("//*[@id=\'ui-
datepicker-div\']/div/div/span[2]")).getText();
int rows = driver.findElements(By.xpath("//table[@class='ui-
datepicker-calendar']/tbody/tr")).size();
int cols=7;

boolean flag=false;

while(true) {
if(month.equals(arr[1]) && year.equals(arr[2])) {
for(int i=1; i<=rows; i++) { // rows tr
for(int j=1; j<=cols; j++) { // columns
String day =
driver.findElement(By.xpath("//table[@class='ui-datepicker-
calendar']/tbody/tr["+i+"]/td["+j+"]")).getText();

if(day.equals(arr[0])) {
driver.findElement(By.xpath("//table[@class='ui-datepicker-
calendar']/tbody/tr["+i+"]/td["+j+"]")).click();
flag=true;
break; // columns stop (inner for loop)
}
}
if(flag) { // stops rows
break; // rows stops (outer for loop)
}
}
if(flag) {
System.out.println("success");
break; // while loop stop
}else {
System.out.println("Please Enter Correct Date");
driver.close();
break;
}
}else {

driver.findElement(By.xpath("//*[@id=\'ui-datepicker-div\']/div/a[2]/
span")).click();
month = driver.findElement(By.xpath("//*[@id=\'ui-datepicker-
div\']/div/div/span[1]")).getText();
year = driver.findElement(By.xpath("//*[@id=\'ui-datepicker-
div\']/div/div/span[2]")).getText();
rows = driver.findElements(By.xpath("//table[@class='ui-
datepicker-calendar']/tbody/tr")).size();
}

}
}
}
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

class Selenium {
public static void main(String[] args) throws InterruptedException {

System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\
chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://jqueryui.com/datepicker/#other-months");

String date = "29-February-2024";


String arr[] = date.split("-"); // index 0

driver.switchTo().frame(0); // frame swift

driver.findElement(By.xpath("//*[@id=\'datepicker\']")).click();

String month = driver.findElement(By.xpath("//*[@id=\'ui-


datepicker-div\']/div/div/span[1]")).getText();
String year = driver.findElement(By.xpath("//*[@id=\'ui-
datepicker-div\']/div/div/span[2]")).getText();

boolean flag=false; // to stop program execution

while(true) {
if(month.equals(arr[1]) && year.equals(arr[2])) {

List days = driver.findElements(By.xpath("//table[@class='ui-


datepicker-calendar']/tbody/tr/td[not(contains(@class,' ui-
datepicker-other-month '))]"));
int size = days.size();

for(int i=0; i<size; i++) { // iterate LIST


WebElement currentday = days.get(i); // reads current
webelement
String day = currentday.getText();

if(day.equals(arr[0])) {
currentday.click();
flag=true;
break; // stops for loop
}
}
if(flag) {
System.out.println("Success");
break; // stops while loop
}else {
System.out.println("Please Enter Valid Date");
driver.close();
break; // stops while loop
}
}else {
driver.findElement(By.xpath("//*[@id=\'ui-datepicker-div\']/div/a[2]/
span")).click();
month = driver.findElement(By.xpath("//*[@id=\'ui-datepicker-
div\']/div/div/span[1]")).getText();
year = driver.findElement(By.xpath("//*[@id=\'ui-datepicker-
div\']/div/div/span[2]")).getText();
}

}
}
}
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;

class Selenium {
public static void main(String[] args) throws InterruptedException {

System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\
chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://jqueryui.com/datepicker/#dropdown-month-
year");
String date = "29-Feb-2024"; //My birthday
String arr[] = date.split("-"); // index 0

driver.switchTo().frame(0); // frame swift

driver.findElement(By.xpath("//*[@id=\'datepicker\']")).click();

Select month = new


Select(driver.findElement(By.xpath("//*[@id=\"ui-datepicker-div\"]/
div/div/select[1]")));

month.selectByVisibleText(arr[1]);

Select year = new


Select(driver.findElement(By.xpath("//*[@id=\"ui-datepicker-div\"]/
div/div/select[2]")));

year.selectByVisibleText(arr[2]);

List days = driver.findElements(By.xpath("//table[@class='ui-


datepicker-calendar']/tbody/tr/td"));
int size = days.size();

boolean flag=false;

for(int i=0; i<size; i++) {


WebElement currentday = days.get(i);
String day = currentday.getText();

if(day.equals(arr[0])) {
currentday.click();
flag=true;
break;
}
}
if(flag) {
System.out.println("Success");
}else {
driver.close();
System.out.println("Please Enter a Valid Date");
}
}

You might also like