Frage

I know that Selenium only supports the CSS selectors that the browser supports. In my HTML app I'm using jQuery but :contains(str) is still throwing me an invalid or illegal string was specified error.

I'm typing text into a Select2 component, waiting 10 seconds, then trying to select the result.

wd.findElement(By.id("s2id_autogen1")).sendKeys(p.getDisplayName());

// Wait 10 seconds

wd.findElement(By.cssSelector(".select2-result-label:contains('"+p.getDisplayName()+"')")).click();

Why am I still getting that error; any ideas? Thank you!

UPDATE: Using xpath is not an option. It must be done using CSS selectors.

War es hilfreich?

Lösung

Use xpath instead of css:

wd.findElement(By.xpath("//[@class='select2-result-label and contains(text(), '"+p.getDisplayName()+"')]")).click();

If you're trying to avoid xpath, you can try this approach instead:

List<WebElement> elements = wd.findElements(By.cssSelector(".select2-result-label"));
WebElement temp;

foreach(WebElement element in elements)
{
    if(element.getText().contains(p.getDisplayName())
        temp = element;
}

It's psuedo-code, as I'm not entirely sure what you're using.

Andere Tipps

Your update mentions this must be done in CSS selector. Well, it can't.

You are missing some of the understanding as to why contains isn't supported. contains is not a CSS selector and is not part of the CSS selector specification. The reason you can use it is because Sizzle implements it. Sizzle is an open source library, which is selector backing engine that jQuery uses.

So the answer is simply it cannot be done using native CSS selectors. You will either have to use XPath (Richard's answer, which, by the way, is the better way to accomplish this) or use JavaScript to execute jQuery on the page. After all, the only reason you can do it is because of Sizzle/jQuery, so you'll still have to use it somehow.

Pseudo Java below:

javascriptDriver = (JavaScriptExecutor)wd;
element = javascriptDriver.executeScript("return $(.select2-result-label:contains('"+p.getDisplayName()+"')");

(assuming that jQuery is mapped to the $ function that is, which, frankly, it should be)

XPath can do this natively, and where it needs to, Selenium will fall back to it's own implementation of XPath (open source library called Wicked Good XPath). If you are testing against modern browsers, you shouldn't have much of an issue (IE being the except).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top