http://www.softwaretestinghelp.com/selenium-webdriver-commands-selenium-tutorial-17/
In the last tutorial, we discussed about the different types of alertsencountered while testing web based applications and their effective ways of handling. We discussed both the types of alerts i.e. “Web-based alerts” and “Window-based alerts” at length. We also made you acquainted with yet another Java based utility named as “Robot Class” to handle windows-based pop up.
Advancing ahead in this Selenium WebDriver tutorial series, we would be pressing on various commonly and routinely used Selenium WebDriver commands. We will precisely and briefly discuss each of these Selenium commands so as to make you capable of using these commands effectively whenever the situation arises. Selenium WebDriver Commands:
Just to have a rough idea, we would be discussing the following Selenium WebDriver commands and their different versions:
-
get() methods
- Locating links by linkText() and partialLinkText()
- Selecting multiple items in a drop dropdown
- Submitting a form
- Handling iframes
-
close() and quit() methods
- Exception Handling
#1) get() Methods
WebDriver command
Usage
get() |
• The command launches a new browser and opens the specified URL in the browser instance • The command takes a single string type parameter that is usually a URL of application under test • To the Selenium IDE users, the command may look very much like open command
driver.get("https://google.com"); |
getClass() |
The command is used to retrieve the Class object that represents the runtime class of this object
driver.getClass(); |
getCurrentUrl() |
• The command is used to retrieve the URL of the webpage the user is currently accessing • The command doesn’t require any parameter and returns a string value
driver.getCurrentUrl(); |
getPageSource() |
• The command is used to retrieve the page source of the webpage the user is currently accessing • The command doesn’t require any parameter and returns a string value • The command can be used with various string operations like contains() to ascertain the presence of the specified string value
boolean result = driver.getPageSource().contains("String to find"); |
getTitle() |
• The command is used to retrieve the title of the webpage the user is currently working on. A null string is returned if the webpage has no title • The command doesn’t require any parameter and returns a trimmed string value
String title = driver.getTitle(); |
getText() |
• The command is used to retrieve the inner text of the specified web element • The command doesn’t require any parameter and returns a string value • It is also one of the extensively used commands for verification of messages, labels, errors etc displayed on the web pages.
String Text = driver.findElement(By.id("Text")).getText(); |
getAttribute() |
• The command is used to retrieve the value of the specified attribute • The command requires a single string parameter that refers to an attribute whose value we aspire to know and returns a string value as a result.
driver.findElement(By.id("findID")). getAttribute("value"); |
getWindowHandle() |
• The command is used to tackle with the situation when we have more than one window to deal with. • The command helps us switch to the newly opened window and performs actions on the new window. The user can also switch back to the previous window if he/she desires.
private String winHandleBefore; winHandleBefore = driver.getWindowHandle(); driver.switchTo().window(winHandleBefore); |
getWindowHandles() |
• The command is similar to that of “getWindowHandle()” with the subtle difference that it helps to deal with multiple windows i.e. when we have to deal with more than 2 windows. |
The code snippet for “getWindowHandles()” is given below:
1 |
public void explicitWaitForWinHandle( final WebDriver dvr, int timeOut, final boolean close) throws WeblivException
|
5 |
Wait<WebDriver> wait = new WebDriverWait(dvr, timeOut);
|
6 |
ExpectedCondition<Boolean> condition = new ExpectedCondition<Boolean>() {
|
9 |
public Boolean apply(WebDriver d) {
|
10 |
int winHandleNum = d.getWindowHandles().size();
|
15 |
for (String winHandle : d.getWindowHandles())
|
17 |
dvr.switchTo().window(winHandle); |
20 |
if (close && dvr.getTitle().equals( "Demo Delete Window" ))
|
22 |
dvr.findElement(By.name( "ok" )).click();
|
#2) Locating links by linkText() and partialLinkText()
Let us access “google.com” and “abodeqa.com” using linkText() andpartialLinText() methods of WebDriver.
The above mentioned links can be accessed by using the following commands:
driver.findElement(By.linkText(“Google”)).click();
driver.findElement(By.linkText(“abodeQA”)).click();
The command finds the element using link text and then click on that element and thus the user would be re-directed to the corresponding page.
The above mentioned links can also be accessed by using the following commands:
driver.findElement(By.partialLinkText(“Goo”)).click();
driver.findElement(By.partialLinkText(“abode”)).click();
The above two commands find the elements based on the substring of the link provided in the parenthesis and thus partialLinkText() finds the web element with the specified substring and then clicks on it.
#3) Selecting multiple items in a drop dropdown
There are primarily two kinds of dropdowns:
-
Single select dropdown: A dropdown that allows only single value to be selected at a time.
-
Multi select dropdown: A dropdown that allows multiple values to be selected at a time.
Consider the HTML code below for a dropdown that can select multiple values at the same time.
1 |
< select id = "SelectID_One" multiple = "" >
|
2 |
< option value = "redvalue" >Red</ option >
|
3 |
< option value = "greenvalue" >Green</ option >
|
4 |
< option value = "yellowvalue" >Yellow</ option >
|
5 |
< option value = "greyvalue" >Grey</ option >
|
The code snippet below illustrates the multiple selections in a drop down.
2 |
Select selectByValue = new Select(driver.findElement(By.id( "SelectID_One" )));
|
3 |
selectByValue.selectByValue( "greenvalue" );
|
4 |
selectByValue.selectByVisibleText( "Red" );
|
5 |
selectByValue.selectByIndex( 2 );
|
#4) Submitting a form
Most or almost all the websites have forms that need to be filled and submitted while testing a web application. User may come across several types of forms like Login form, Registration form, File Upload form, Profile Creation form etc.
In WebDriver, user is leveraged with a method that is specifically created to submit a form. The user can also use click method to click on the submit button as a substitute to submit button.
Check out the code snippet below against the above “new user” form:
2 |
driver.findElement(By.<em>id</em>( "username" )).sendKeys( "name" );
|
5 |
driver.findElement(By.<em>id</em>( "email" )).sendKeys( "name@abc.com" );
|
8 |
driver.findElement(By.<em>id</em>( "password" )).sendKeys( "namepass" );
|
11 |
driver.findElement(By.<em>id</em>( "passwordConf" )).sendKeys( "namepass" );
|
14 |
driver.findElement(By.<em>id</em>( "submit" )).submit();
|
Thus, as soon as the program control finds the submit method, it locates the element and triggers the submit() method on the found web element.
#5) Handling iframes
While automating web applications, there may be situations where we are required to deal with multiple frames in a window. Thus, the test script developer is required to switch back and forth between various frames or iframes for that matter of fact.
An inline frame acronym as iframe is used to insert another document with in the current HTML document or simply a web page into another web page by enabling nesting.
Consider the following HTML code having iframe within the webpage:
2 |
< head >< title >Software Testing Help - iframe session</ title >
|
6 |
< iframe id = "ParentFrame" >
|
7 |
< iframe id = "ChildFrame" >
|
8 |
< input type = "text" id = "Username" >UserID</ input >
|
9 |
< input type = "text" id = "Password" >Password</ input >
|
11 |
< button id = "LogIn" >Log In</ button >
|
The above HTML code illustrates the presence of an embedded iframe into another iframe. Thus, to be able to access the child iframe, user is required to navigate to the parent iframe first. After performing the required operation, user may be required to navigate back to the parent iframe to deal with the other element of the webpage.
It is impossible if a user tries to access the child iframe directly without traversing to the parent iframe first.
Select iframe by id
driver.switchTo().frame(“ID of the frame“);
Locating iframe using tagName
While locating an iframe, user might face some trouble if the iframe is not attributed with standard properties. It becomes a complex process to locate the frame and switch to it. To buckle down the situation, user is leveraged to locate an iframe using tagName method similar to the way we find any other web element in WebDriver.
driver.switchTo().frame(driver.findElements(By.tagName(“iframe”).get(0));
The above command locates the first web element with the specified tagName and switches over to that iframe. “get(0) is used to locate the iframe with the index value.” Thus, in lines with our HTML code, the above code syntax would lead the program control to switch to “ParentFrame”.
Locating iframe using index:
a) frame(index)
driver.switchTo().frame(0);
b) frame(Name of Frame)
driver.switchTo().frame(“name of the frame”);
c) frame(WebElement element)
Select Parent Window
driver.switchTo().defaultContent();
The above command brings the user back to the original window i.e. out of both the iframes.
#6) close() and quit() methods
There are two types of commands in WebDriver to close the web browser instance.
a) close(): WebDriver’s close() method closes the web browser window that the user is currently working on or we can also say the window that is being currently accessed by the WebDriver. The command neither requires any parameter nor does it return any value.
b) quit(): Unlike close() method, quit() method closes down all the windows that the program has opened. Same as close() method, the command neither requires any parameter nor does it return any value.
Refer the below code snippets:
driver.close(); // closes only a single window that is being accessed by the WebDriver instance currently
driver.quit(); // closes all the windows that were opened by the WebDriver instance
#7) Exception Handling
Exceptions are the conditions or situations that halt the program execution unexpectedly.
Reasons for such conditions can be:
- Errors introduced by the user
- Errors generated by the programmer
- Errors generated by physical resources
Thus, to deal with these unexpected conditions, exception handling was conceptualized.
With respect to Java code that we implement while automating a web application can be enclosed within a block that that is capable of providing a handling mechanism against the erroneous conditions.
Catching an exception
To catch an exception, we use the below block of code
5 |
catch (ExceptionName e)
|
If any exception occurs in the try block/protected block, then the execution controls checks for a catch block for the matching exception type and passes the exception to it without breaking the program execution.
Multiple Catch Blocks
4 |
catch (ExceptionType1 e)
|
8 |
catch (ExceptionType2 e)
|
12 |
catch (ExceptionType3 e)
|
In the above code, exception is likely to be caught in the first catch block if the exception type matches. If the exception type does not match, then the exception is traversed to the second catch block and third catch block and so on until the all catch blocks are visited.
WebDriver conditions and Exception Handling
When we aspire to verify the presence of any element on the webpage using various WebDriver ‘s conditional commands, WebDriver presumes the web element to be present on the web page. If the web element is not present on the web page, the conditional commands throw a “NoSuchElementPresentException”. Thus to avoid such exceptions from halting the program execution, we use Exception Handling mechanisms. Refer the code snippet below:
1 |
WebElement saveButton = driver.findElement(By.id( "Save" ));
|
3 |
if (saveButton.isDisplayed()){
|
7 |
catch (NoSuchElementException e){
|
Conclusion
In this tutorial, we introduced various WebDriver’s commonly and excessively used commands. We tried to explain the commands with the suitable examples and code snippets.
Next Tutorial #18: In the upcoming tutorial, we would discuss aboutWeb tables, frames and dynamic elements which are essential part of any web project. We will also cover the exception handlingimportant topic in more details in one of the upcoming Selenium Tutorials.
相关推荐
【Python的selenium操作:判断元素是否存在】 在Python的自动化测试中,Selenium是一个非常强大的工具,用于模拟用户与网页的交互。Selenium库提供了一系列API,使得我们可以控制浏览器进行各种操作,例如点击按钮...
首先,Selenium WebDriver 是Selenium的一个组件,它用于控制浏览器进行自动化操作。ChromeDriver是专门为谷歌浏览器设计的一个WebDriver实现,它作为桥梁,使得Selenium可以与Chrome浏览器进行通信,执行如点击、...
Selenium WebDriver 3 Practical Guide will walk you through the various APIs of Selenium WebDriver, which are used in automation tests, followed by a discussion of the various WebDriver implementations...
Selenium:SeleniumWebDriver基础操作教程.docx
Selenium WebDriver 是一款广泛使用的自动化测试工具,专为Web应用程序设计。它允许程序员模拟真实用户在浏览器中的操作,如点击、输入、导航等,从而进行功能性和兼容性测试。了解其工作原理对于优化自动化测试脚本...
在“selenium-practice:学习Selenium WebDriver:robot::microscope:”这个项目中,我们主要关注的是Selenium WebDriver的使用,这是一个用于自动化浏览器操作的接口。WebDriver通过模拟用户行为来测试网页,例如点击...
Selenium WebDriver是一款强大的自动化测试工具,它允许程序员模拟真实用户在浏览器上的操作,进行Web应用程序的功能测试和验收测试。在Java环境下,Selenium WebDriver通常需要引入相应的jar包才能正常工作。...
Selenium2 WebDriver 中文文档完整 Selenium2 WebDriver 是一个流行的自动化测试工具,用于模拟用户交互来测试Web应用程序。本文档将详细介绍 Selenium2 WebDriver 的安装、配置、基本操作和使用技巧。 安装 ...
在Selenium的众多组件中,WebDriver是核心的一部分,它提供了与不同浏览器交互的能力。在本文中,我们将深入探讨如何使用Selenium WebDriver处理网页中的弹出窗口。 ### Selenium WebDriver与弹出窗口 #### 弹出...
4. **Browser Specific Drivers**:每个浏览器的驱动程序(如 `org.openqa.selenium.chrome.ChromeDriver` 和 `org.openqa.selenium.firefox.FirefoxDriver`)实现了 WebDriver 接口,实现了与不同浏览器的交互。...
本书是一本从入门到精通模式的Selenium WebDriver实战经验分享书籍。全书共分为四个部分:第1部分基础篇主要讲解自动化测试相关的基础理论、WebDriver 环境安装、单元测试工具的使用方法以及 WebDrvier的入门使用...
"selenium+webdriver学习文档" 本文档主要介绍了使用 Selenium+WebDriver 进行自动化测试的学习方法,从基础到精通的学习方法。下面我们将对标题、描述、标签和部分内容进行详细的解释。 标题:selenium+webdriver...
**Selenium WebDriver** 是一个广泛使用的自动化测试工具,主要用于网页应用程序的测试。它模拟了真实用户的浏览器行为,允许测试人员编写脚本来控制浏览器执行各种操作,如点击按钮、填写表单、导航等。WebDriver ...
### selenium webdriver基于python源码案例 #### 一、Selenium简介与环境搭建 **1.1 Selenium概述** Selenium是一个强大的工具集,主要用于自动化Web应用的测试。它支持多种编程语言,如Java、C#、Python等,并能...
【标题】"selenium webdriver+chrome插件.zip" 涉及的核心知识点是Selenium WebDriver,特别是它在Chrome浏览器中的应用以及与Firefox的交互。这个压缩包包含了Selenium IDE的Chrome插件,以及对应的WebDriver驱动...
Ruby+Selenium-Webdriver是一个强大的自动化测试工具组合,用于模拟真实用户在浏览器中与网页进行交互。Ruby是一种动态、面向对象的编程语言,而Selenium WebDriver是一个开源的自动化测试框架,支持多种浏览器和...
自动化测试:Selenium webdriver学习笔记 C#版 在本篇笔记中,我们将讨论 Selenium webdriver 的自动化测试中的对象定位方法。对象定位是自动化测试中非常重要的一步骤,它决定了我们的测试脚本是否能够正确地找到...