How to Find a web element in Selenium Webdriver

In this article, we are going to see the functions needed to find a web element from a webpage from code using selenium web driver. I am using c# code to do that.

First, every element of an webpage are following IWebElement contract(similar to web element class) . So we need to declare that. The code will be -
private IWebElement element;

Now, we need to assign the element by finding using driver. We can find a web element in eight ways.
1. To find elements by their CSS class(web driver has different class for different type css)
element = driver.FindElement(By.ClassName("String"));

2. To find elements by their cascading stylesheet (CSS) selector
element = driver.FindElement(By.CssSelector("string"));

3. To find elements by their ID(maintained id in full page)
element = driver.FindElement(By.Id("String"));

4. To find elements by their link text(link showing text)
element = driver.FindElement(By.LinkText("String"));

5. To find elements by their name(maintained name in full page)
element = driver.FindElement(By.Name("String"));

6. To find elements by a partial match on their link text(not exac match with link text)
element = driver.FindElement(By.PartialLinkText("String"));

7. To find elements by their tag name
element = driver.FindElement(By.TagName("String"));

8. To find elements by an XPath query
element = driver.FindElement(By.XPath("String"));

Note : Xpath query is the most convenient way to use in dynamic web page. we should learn about xpath also.

...thanks.:) .. if selenium versions updated, I will update the finding ways.

2 comments:

  1. Hi dada, how to locate elements in angularJS application using selenium webdriver?

    ReplyDelete
    Replies
    1. If items are pre populated, you can get by selectors. (advance selectors Pseudo selectors like http://www.w3schools.com/css/css_pseudo_classes.asp)
      if items are coming dynamically by Ajax,
      => you need to refresh or repopulate (init element) with keep bowser session safe(keep the same session)
      or => Use javaScript executor to run javascripts to get the element.

      Delete