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.
相关推荐
博客附带源码以及selenium在Python和PyCharm中的安装方法链接,欢迎大家一起交流学习,共同进步,此方式是自己通过实际操作,而总结出来的,欢迎大家批评指正!
Selenium WebDriver is an open source web UI automation tool implemented through a browser-specific browser driver, which sends commands to a browser and retrieves results. Selenium WebDriver ...
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 RC与selenium webdriver的区别
selenium开发:谷歌浏览器和驱动配套版本,很哪找。试了很多版本,这个是版本的浏览器和驱动是配套的,谷歌驱动只有32位,但是32和64都是通用的
Selenium WebDriver Recipes in C#, Second Edition contains hundreds of solutions to real-world problems, with clear explanations and ready-to-run Selenium test scripts that you can use in your own ...
Selenium是ThroughtWorks公司一个强大的开源Web功能测试工具系列,本系列现在主要包括以下4款: 1.Selenium Core:支持DHTML的测试案例(效果类似数据驱动测试),它是Selenium IDE和Selenium RC的引擎。 2....
关于Selenium WebDriver工作原理的介绍,原理相关描述
selenium-webdriver原创selenium-webdriver原创selenium-webdriver原创selenium-webdriver原创
描述:使用Python,PyTest和Selenium WebDriver演示网站的UI测试自动化。 平台(目前):达尔文 支持的浏览器(目前): Chrome版本87.0.4280.67 Firefox版本84.0.2 特征 Selenium Webdriver(Python绑定) ...
Selenium基础Selenium WebDriver自动化和测试实践的仓库。
自动化测试:Selenium webdriver学习笔记C#版
本书是一本从入门到精通模式的Selenium WebDriver实战经验分享书籍。全书共分为四个部分:第1部分基础篇主要讲解自动化测试相关的基础理论、WebDriver 环境安装、单元测试工具的使用方法以及 WebDrvier的入门使用...
Selenium-Webdriver系列教程 Selenium 1.x时代已经远去,它理应躺在历史的角落里,靠着壁炉烤着火,抽着旱烟,在袅袅的升起的青烟中回忆那曾经属于自己的美好时代。 不过事实却并非如此,现今原本早应退役的...
Selenium WebDriver 3.14.0 本来需要.net45 我改为.net2.0 希望喜欢的人需要。 dll 反编译,嵌入程序内。无需调用那个讨厌的dll。 绝对不骗人,骗人是小狗。架构复杂修改麻烦,各位体谅
Selenium WebDriver API的基础用法均整理自网络,有意义学习参考默认路径指定路径close()或quit() 最大化() SetSize()得到() navigation()。to()和navigation()。to()。back()/ forward()找到...
The second edition of Mastering Selenium 3.0 WebDriver starts by showing you how to build your own Selenium framework with Maven. You’ll then look at how you can solve the difficult problems that you...
用于firefox录制的插件,是php语言的文件导出,使用firefox打开的话下载完成后直接安装。
selenium-webdriver-2.40.0.gem
selenium-webdriver-2.5.0.gem