Saturday, May 24, 2014

Web Driver API commands and UI Elements

Selenium Web Driver API commands

Get your web page

By calling get, you can get your web page.
driver.get("http://www.google.com");

Web Elements

By ID
For locating the UI elements(Web Elements) , you can use WebElement.

See below example,
<div id="languages">
   .........
   .........
   .........
</div>

Now you can get that above element through below command.
WebElement element = driver.findElement(By.id("languages"));

By Class Name
The same concept you can apply to all other UI elements. But it will differ little.

See below example,
<div class="border"><span>RED</span></div>
<div class="border"><span>GREEN</span></div>

List<WebElement> border = driver.findElements(By.className("border"));

Above we are using className method, due to it belongs to class DOM.
and why we are using List, since the class name might be present in multiple places.

By Tag Name
Same concept DOM tag name should mentioned here.

See below example,
<iframe src="..."> </iframe>

WebElement frame = driver.findElement(By.tagName("iframe"));

By Name
You can find the element for an input element.

See below example,
<input name="javahit" type="text"/>

WebElement javaHit = driver.findElement(By.name("javahit"));

By Link Text
You can find the link element with matching visible text.

See below example,
<a href="http://www.google.com/search?q=test">test</a>>

WebElement Test = driver.findElement(By.linkText("test"));

By Partial link text
You can find the link element with partial matching visible text.

See below example,
<a href="http://www.google.com/search?q=color">search for color</a>>

WebElement Color = driver.findElement(By.partialLinkText("color"));

By CSS
It is a locator strategy by CSS. It should be handled with care. since browser version will differ.

<div id="test"><span class="sample">water</span><span class="sample ok">Checking CSS</span></div>

WebElement Checking CSS = driver.findElement(By.cssSelector("#test span.sample.ok"));

By XPATH
Mostly webDriver uses native XPATH, wherever possible cases. Suppose if the browser dont have native XPATH support, you have to give your own implementation.
So you should know the difference various XPATH engines.

Driver
Tag and Attribute Name
Attribute Values
Native XPath Support
HtmlUnit Driver
Lower-cased
As they appear in the HTML
Yes
Internet Explorer Driver
Lower-cased
As they appear in the HTML
No
Firefox Driver
Case insensitive
As they appear in the HTML
Yes

See the below example carefully. So that you can understand this XPATH concept clearly.

<input type="text" name="java" />
<INPUT type="text" name="hit" />

Above I given one input as in Small Letter and another one as Capital Letter.
List<WebElement> inputs = driver.findElements(By.xpath("//input"));

See the below table now.

XPath expression
HtmlUnit Driver
Firefox Driver
Internet Explorer Driver
//input
1 (“java”)
2
2
//INPUT
0
2
0


No comments:

Post a Comment