Sunday, 16 March 2014

How to find the element with selenium webdriver in C#.Net?


We can identify the web elements in selenium webdriver using below 8 methods in C#.Net.
  1. By Xpath
  2. By Css Selectors
  3. By Id
  4. By Name
  5. By Tag Name
  6. By Class Name
  7. By Linktext
  8. By Partial Link text
Out of these methods, xpath and css selector methods are very popular and useful. We can use xpath and css selectors to identify all kinds of elements in the webpage.

We can also identify the elements using Id, Name, Class Name provided that given element is assigned some id, name or class name.

We can also identify the elements using the html tags like table, div, form etc. 

For identifying the links, selenium web driver provides 2 additional methods like link text and Partial link text.

Web Element Identification Examples in C#.Net

Below method will return the first element with given tag - A.
IWebElement we = driver.findElement(By.TagName(“A”));

You can also access the element if you know its class name by using below code
IWebElement we = driver.findElement(By.ClassName(“highlight”));

You can access the element if you know its id by using below code
IWebElement we = driver.findElement(By.Id(“next”));

You can also access the element if you know the value of name attribute by using below code
IWebElement we = driver.findElement(By.Name(“submit”));

To find the links in web page, there are 2 ways as mentioned below.
IWebElement we = driver.findElement(By.LinkText
 (“news”));

If you know the part of the name of link, you can use By.partialLinkText
IWebElement we = driver.findElement(By.PartialLinkText(“news”));

You can also access the element if you know its xpath expression by using below code
driver.FindElement(By.XPath("//a[contains(@href,'google')]")).Click();

You can also access the element if you know its css expression by using below code
IWebElement we = driver.FindElement(By.CssSelector("#shadow"));


We.click();

To find all elements you can use below syntax.

We have 2 methods to find the elements in the webpage.

  1. FindElement - returns first matching element
  2. FindElements - returns collections of all matching elements
For example - suppose we have to find all elements having name - gender then we can use below code


ReadOnlyCollection <IWebElement> ec = driver.FindElements(By.Name("gender"));
for (int k=0;k<ec.Count;k++)

Console.WriteLine("which gender selected ?" + ec[k].Selected);

What do you think on above selenium topic. Please provide your inputs and comments. Thanks

2 comments:

Buy Best Selenium Books

Contributors