Alternative of contains in cssSelector ? Selenium WebDriver

1,908 views
Skip to first unread message

Abu Hamzah

unread,
Jan 29, 2013, 8:23:15 PM1/29/13
to webd...@googlegroups.com
I am using selenium 2 (WebDriver)

I am locating a button and clicking by the script : ' 

    driver.findElement(By.cssSelector("button:contains('Run Query')")); 
    
    or 
    
    driver.findElement(By.cssSelector("css=.gwt-Button:contains('Run Query')")) 

whose html is like : 

    <button type="button" class="gwt-Button" id="ext-gen362">Run Query</ 
    button> 

as the id is dynamically generated I cant make use of the ID. 

is there any way to use cssSelector with something like contains ? possible?

Jim Evans

unread,
Jan 30, 2013, 6:12:05 AM1/30/13
to webd...@googlegroups.com
No, it's not possible.

Oh, you were looking for something with a little more detail? The :contains pseudoselector is not part of any CSS standard created be the World Wide Web Consortium (W3C). Unfortunately, Sizzle, the CSS selector engine used by jQuery, implements :contains, and many people don't realize that despite its near-ubiquity, it's still not a standard. Since WebDriver uses the browsers' native CSS selector engine when possible, that means it doesn't have access to selectors that the native selector engine doesn't implement. And that means :contains. This is one of the few times I suggest XPath over CSS selectors.

shabbir

unread,
Jan 30, 2013, 6:28:20 AM1/30/13
to webd...@googlegroups.com
If the class name is not changing then you should be able to get the element as:

driver.findElement(By.ClassName("wt-Button"))

If there are multiple for this class name, then use findElements

darrell

unread,
Jan 30, 2013, 7:25:47 AM1/30/13
to webd...@googlegroups.com
Typically, you would use:

    driver.findElement(By.cssSelector("button.gwt-Button"));

To the left of the period (.) is the tagname and to the right of the period is the class name. You can also use:

    "button[class='gwt-Button']"      // exact match
    "button[class~='gwt-Button']"    // contains word
    "button[class*='gwt-Button']"     // class contains substring

All the CSS selectors will deal with the attributes inside the tag. The data between the open and close tag isn't used by CSS. For that you need to use an XPath, e.g.

    By.xpath("//button[contains(text(), 'Run Query')]")

Darrell
Reply all
Reply to author
Forward
0 new messages