:contains selector with Selenium and Select2

随声附和 提交于 2019-12-23 05:39:31

问题


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.


回答1:


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.




回答2:


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).



来源:https://stackoverflow.com/questions/22815625/contains-selector-with-selenium-and-select2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!