We can identify the web elements in selenium webdriver using below 8 methods in C#.Net.
- By Xpath
- By Css Selectors
- By Id
- By Name
- By Tag Name
- By Class Name
- By Linktext
- 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”));
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.
- FindElement - returns first matching element
- 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);
Very Helpful Examples.Thanks
ReplyDeleteExcellent! Very helpful indeed.
ReplyDelete