Assuming there are no differences between your screenshots and what you're really working with, the likely reason your code snippet isn't working is because you must use the entire id name which would be select2-section-1k-container
. If you want to target it with a partial name, you can do something more like: By.cssSelector([id*='section-1k'])
which will target any element whose id contains that sub-string. Make sure though that it doesn't target more than one element though, otherwise you'll end up talking to the wrong one.
Edit:
If I'm understanding correctly, the 1k in your id may change, but no other parts of it. Assuming that we're going to always have select2-section-
before and -container
after... You could target those two sections separately [id^='select2-section'][id$='container']
In this css example, we're saying that we want to target an element whose attribute (id in our case) starts with a value, but also ends with a value. Those rules are described with:
*= contains substring
^= values begins with
$= value ends with
Edit 2:
Sorry, I should've included an example of how to actually use it too...
By myBy = By.cssSelector("[id^='select2-section'][id$='container']");
WebElement myElement = driver.findElement(myBy);
Select select = new Select(myElement);
Edit 3:
At this point, you seem to be using correct syntax for what you're trying to do. So you need to determine why the selector you're trying to use isn't working. That's not something anyone is going to be able to give you an answer for unless you share the real web page with the elements you need help with.
A few reasons that it could be failing, however:
Using ^= to find a value that isn't the true beginning
Using $= to find a value that isn't the true end
The css selector you're using is locating more than one element, such that the one you intended isn't the first found.
You can find browser addons that let you more easily validate css selectors and will highlight any and all elements that match a css selector you provide. But in the absense of a browser addon, you can use the browser console to test 1-off selectors. The way you do this differs a bit depending on whether you want to use vanilla js, or another such as jquery.
I'm less familiar how to do it with vanilla js, but you can quickly test if a web page uses jquery by typing $("")
, $$("")
or $j("")
. If any of those do NOT give you an error for not being defined, then you have that version of jquery, and you can put css selectors inside those quotes to test directly in the browser. This is a good tool for testing your css selectors and quickly making tweaks before running your potentially bulky and more time consuming test(s).