Link to home
Start Free TrialLog in
Avatar of Sri
Sri

asked on

Selenium how to know the locator type dynamically

In selenium is it possible to know the type of the locator whether it is given in css or xpath or id or name or linktext etc..

the requirement is i get the locator in the form of a string and i have to know whether it is CSS or xpath

By selector = driver.findElement(By.cssSelector(locator));

if(selector == null){

  selector = driver.findElement(By.xpath(locator)); }

Open in new window

as the very first statement throws an exception if it is a different locator, is there an easy way that we can identify the type and handle and type of locator
Avatar of mccarl
mccarl
Flag of Australia image

Can't you just catch the exception then?
By selector = null;

try {
    selector = driver.findElement(By.cssSelector(locator));
} catch (Exception ex) {}

if (selector == null) {
    selector = driver.findElement(By.xpath(locator));
}

Open in new window




Also, shouldn't the code be more like this?
WebElement element = null;

try {
    element = driver.findElement(By.cssSelector(locator));
} catch (Exception ex) {}

if (element == null) {
    element = driver.findElement(By.xpath(locator));
}

Open in new window

Avatar of Sri
Sri

ASKER

Thanks for responding mccarl, so now if i want to check with Id or tagName again i have to write few more try blocks? isn't there generic method  that takes any locator and finds the element that we wanted
ASKER CERTIFIED SOLUTION
Avatar of mccarl
mccarl
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Sri

ASKER

Thanks mccarl
You're welcome