Tuesday, 5 August 2014

Element Identification using Selenium WebDriver: Questions and Answers

1: What is the method used to launch URL using Selenium WebDriver?
Answer: In Firefox, we can set the homepage as the required URL as shown in the code below. This will launch the URL set in homepage on launching the driver.
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference(“browser.startup.homepage”,“http://www.google.com”);
//We will provide the profile used as argument for Firefox Driver.
WebDriver driver = new FirefoxDriver(profile);
In case, we do not want to use profile, we can use the get method to launch the URL.
WebDriver driver = new FirefoxDriver();
driver.get(“https://www.google.com”);
2: What is the difference between findElement and findelements method in Selenium?
Answer: To locate an element in the page, we use findElement method whereas findElements gives the collection of web elements in the Page.
Syntax for findElement is:
WebElement tableinfo = driver.findElement(By.className(“tableClsName”));
This will give the first element in the page with className as “tableClsName”. Now once the element is recognized, we can perform action on the WebElement. Suppose the element is a button, we can click on the button as shown below:
Tableinfo.click();
Suppose the WebElement is an input box, we can insert data in the input box as shown below:
Tableinfo.SendKeys(“This is a test”);
Syntax for findElements is:
List<WebElement> tabledata = tableinfo.findElements(By.tagName(“td”));
This will give collection of all elements in the page with className as “td”.
We can further work on the collection of the object and extract the required information or perform actions on the required webElement as shown below:
List<WebElement> tabledata = tableinfo.findElements(By.tagName(“td”));
for (int iCnt = 0;i<tabledata.size();iCnt++)
 {
String strData = tabledata.get(iCnt).getText() ;
If(strData.contentEquals(“this is the row”))
{
System.out.println(“Web Element Found”)
iCnt = tabledata.size()-1;
}
}
3: What are the value ways to identify an object in Selenium WebDriver?
Answer: Below are the various locators by which elements can be identified in Selenium WebDriver:
1. Id:  Identifies WebElement by the ‘Id’ attribute.
2. ClassName: Identifies webelement by the ‘class’ attribute.
3. cssSelector: identifies element based on the css of the webElement.
4. linkText: Identifies element by the actual text of the link. Text should match exactly with the link text.
5. Name: Identifies webelement by the ‘name’ attribute.
6. partiallinkText: Identifies element by the actual text of the link. The link is identified on partial match of text.
7. tagName: Identifies an object by the tagName of the webElement.
8. xpath: Identifies an object by the xpath of the object.

No comments:

Post a Comment