0

I use simple code as

 [FindsBy(How = How.CssSelector, Using = "div[id=1]")]
 private IWebElement _plasticOption;

to find element with id = 1.

It's for page factory, if someone don't know what it is, we can change the code above to the next one:

 IWebElement element = driver.FindElement(By.CssSelector("div[id=1]"));

So, this simple code can't find an element in the next piece of HTML:

<div class="b-wide-option disabled" data-bind="css: { selected: IsSelected, disabled: !IsVisible() }, click: Select, attr: { id: Id }" id="1"> </div>

But I can simply find this element the next way:

 [FindsBy(How = How.Id, Using = "1")]
 private IWebElement _plasticOption;

And I actually wonder why I can't find this element using CssSelector.

I have:

selenium webdriver v.2.43.1

chromedriver v. 2.10

Chrome Brovser v. 37.0.2062.120

3
  • Have you tried using a # symbol for the id? eg, By.CssSelector("div#1") ? Commented Sep 18, 2014 at 10:12
  • Yes I have, also I've tried using just # without tag name Commented Sep 18, 2014 at 10:23
  • @Mark Rowlands: See my answer for why that won't work either as is. Commented Sep 18, 2014 at 10:37

1 Answer 1

3

[id=1] is not a valid attribute selector. When the attribute value is unquoted, it's treated as a CSS identifier, and a CSS identifier cannot start with a digit. It is for this same reason that a selector like div#1 will not work.

If you need to look for an attribute value that starts with a digit, you need to quote the value:

[FindsBy(How = How.CssSelector, Using = "div[id='1']")]
private IWebElement _plasticOption;

If you prefer to use an ID selector, you need to escape the digit (you could also do this in the attribute selector, but you'd be better off just quoting the value instead):

[FindsBy(How = How.CssSelector, Using = "div#\\1")]
private IWebElement _plasticOption;
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot! It works now! Unfortunately I'm not allowed to vote up your answer(
That's OK, for now you can mark it as the correct answer using the icon below the vote arrows. Glad I could help!
@BoltClock I hadn't come across that particular issue before, thanks for the clarification.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.