2

How it locate or identify the element using the type like id, class, etc. Moreover BY is an abstract class. How we create object for it if possible? We know we cannot create object directly for an abstract without implementing it by an another class. I would like to know the scenario behind it before we are directly using in our scripts

public abstract class By extends java.lang.Object

I have gone through the link "https://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/By.html"

Sanjay Bhimani
  • 1,593
  • 1
  • 15
  • 29
  • your answer is [here](http://stackoverflow.com/questions/17407203/can-we-use-static-method-in-an-abstract-class). You need to understand abstract class concept for this. – Mrunal Gosar Jan 20 '16 at 06:47

2 Answers2

3

I had also required same functionality, but instead of creating object I implemented By functionality using below code. Basically findElement method use By to locate elements.

String xPath = "xpath=//*[@text='some text']";
//String xPath = "name='some text'";
//String xPath = "id=xxxx";

driver.findElement(getBy(xPath));

private By getBy(String locator) {
    String[] parts = locator.split("=", 2);
    By by = null;
    switch (parts[0].trim()) {
    case "xpath":
        by = By.xpath(parts[1]);
        break;
    case "name":
        by = By.name(parts[1]);
        break;
    case "link":
        by = By.linkText(parts[1]);
        break;
    case "id":
        by = By.id(parts[1]);
        break;
    case "css":
        by = By.cssSelector(parts[1]);
        break;
    default:
        throw new RuntimeException("invalid locator");
    }
    return by;
}

Hope this will help you.

Sanjay Bhimani
  • 1,593
  • 1
  • 15
  • 29
0

You don't need to understand the implementation of selenium. You just need to know how to use it.

If you have autocomplete in your IDE and type By. you will see a lot of static methods defined in this By class.

Here is an example

Borislav Stoilov
  • 3,247
  • 2
  • 21
  • 46