简体   繁体   中英

Selenium WebDriver issue with By.cssSelector

I have an element whose html is like :

<div class="gwt-Label textNoStyle textNoWrap titlePanelGrayDiagonal-Text">Announcements</div> 

I want to check the presence of this element. So I am doing something like :

WebDriver driver = new FirefoxDriver(profile);
driver.findElement(By.cssSelector(".titlePanelGrayDiagonal-Text"));

But its not able to evaluate the CSSSelector.

Even I tried like :

By.cssSelector("gwt-Label.textNoStyle.textNoWrap.titlePanelGrayDiagonal-Text")

tried with this as well :

By.cssSelector("div.textNoWrap.titlePanelGrayDiagonal-Text")

Note : titlePanelGrayDiagonal-Text class is used by only this element in the whole page. So its unique. Contains pseudo selector I can not use. I want to identify only with css class.

Versions: Selenium 2.9 WebDriver Firefox 5.0

When using Webdriver you want to use W3C standard css selectors not sizzle selectors like you may be used to using in jquery. In your example you would want to use:

driver.findElement(By.cssSelector("div[class='titlePanelGrayDiagonal-Text']"));

I haven't used css selectors, but this is the xpath selector I would use:

"xpath=//div[@class='gwt-Label textNoStyle textNoWrap titlePanelGrayDiagonal-Text']"

The css selector should then probably be something like

"css=div[class='gwt-Label textNoStyle textNoWrap titlePanelGrayDiagonal-Text']"

Source: http://release.seleniumhq.org/selenium-remote-control/0.9.2/doc/dotnet/Selenium.html

From reading over your post what you should do since that class is unique is just do a FindElement(By.ClassName("titlePanelGrayDiagonal-Text"));

Also the CssSelector doesn't handle the contains keyword it was something that the w3 talked about but never added.

I believe using a wildcard in CSS would be more helpful. Something as follows driver.findElement(By.cssSelector("div[class$='titlePanelGrayDiagonal-Text']");

This will look into the class attribute and see what that attribute is ending with. Since your class attribute is ending with "titlePanelGrayDiagonal-Text" string, the added '$' in the css statement will find the element and then you can perform whatever action you're trying to perform.

Did you ever tried following code,

By.cssSelector("div#gwt-Label.textNoStyle.textNoWrap.titlePanelGrayDiagonal-Text");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM