Falcon25
Falcon25

Reputation: 23

Get CSS selector string from WebElement in Selenium WebDriver - Java

I have a WebElement and I'm simply trying to extract the CSS selector string. This is the value of the variable when I debug the code:

[[ChromeDriver: chrome on MAC (345345345n5435345b34)] -> css selector: div[class='alert alert-danger']]

I need to have access to just the css selector:

div[class='alert alert-danger']]

I could split the string, but does anyone know of a more efficient method that Selenium provides? I've tried using .getAttribute("class") which returns "alert alert-danger" but I need the entire selector.

Thank you for reading, any help would be much appreciated.

Upvotes: 2

Views: 7699

Answers (3)

Doctor Strange
Doctor Strange

Reputation: 351

No you cannot do it any easier. Also, note that the selector that you will obtain will have no guarantee of targeting the element in question uniquely. Check out the link for some more insights https://stackoverflow.com/a/19843175/6184852
It'll be easier to figure out the selector from how you ended up getting the element.

Upvotes: 0

Florent B.
Florent B.

Reputation: 42538

You can build your own unique CSS selector with a piece a Javascript. Here is an example with Java:

final String JS_BUILD_CSS_SELECTOR =
    "for(var e=arguments[0],n=[],i=function(e,n){if(!e||!n)return 0;f" +
    "or(var i=0,a=e.length;a>i;i++)if(-1==n.indexOf(e[i]))return 0;re" +
    "turn 1};e&&1==e.nodeType&&'HTML'!=e.nodeName;e=e.parentNode){if(" +
    "e.id){n.unshift('#'+e.id);break}for(var a=1,r=1,o=e.localName,l=" +
    "e.className&&e.className.trim().split(/[\\s,]+/g),t=e.previousSi" +
    "bling;t;t=t.previousSibling)10!=t.nodeType&&t.nodeName==e.nodeNa" +
    "me&&(i(l,t.className)&&(l=null),r=0,++a);for(var t=e.nextSibling" +
    ";t;t=t.nextSibling)t.nodeName==e.nodeName&&(i(l,t.className)&&(l" +
    "=null),r=0);n.unshift(r?o:o+(l?'.'+l.join('.'):':nth-child('+a+'" +
    ")'))}return n.join(' > ');";

WebDriver driver = new FirefoxDriver();
JavascriptExecutor js = (JavascriptExecutor)driver;
driver.get("http://stackoverflow.com/questions");

// get an element
WebElement element = driver.findElement(By.cssSelector(".youarehere"));

// build the Css selector for the targeted element
String selector = (String)js.executeScript(JS_BUILD_CSS_SELECTOR, element);

// display the result
System.out.println("Unique Css selector: " + selector);

Upvotes: 3

Roman
Roman

Reputation: 3941

One simple way would be to use regex. From the given string you provided you could extract the whole selector by using the following regex expression:

div.*

See Regex101

Sometimes you have other elements (not always div), so you could create a method which takes this as an argument, so you can use the same for for example: ul.* etc.

Upvotes: 0

Related Questions