Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm trying to use css selector to get an element inside a <li> with Selenium

That's I have:

<div id= "popup">
  <ul>
     <li>
        <div id="item" option= "1" ....> </div>
     </li>
     <li>
        <div id="item" option= "2" ....> </div>
     </li>
  </ul>
 </div>

I need to get the second div, with option=2. I tried:

webdriver.findElement(By.cssSelector("#popup > ul li:nth-child(n) [option=2]");

that works fine in console of Chrome but not with Selenium :/ What's wrong with this?

share|improve this question
add comment

2 Answers

Two issues:

  • :nth-child(n) means "any value of n" which will result in every child being matched. You probably mean to use :nth-child(2) if you want to make sure you only get the element under the second li. Or if it doesn't matter which li it appears in, you can get rid of the :nth-child() selector entirely.

  • The value in an attribute selector must be quoted if it begins with a digit, so [option='2'].

The correct selector, therefore, is:

webdriver.findElement(By.cssSelector("#popup > ul li:nth-child(2) [option='2']");
share|improve this answer
    
Yeah "#popup > ul li:nth-child(2) [option='2']" work´s fine, but i need select element with [option='2'] but i dont know position in the list. :nth-child() does not work. Finaly i use: "#popup > ul li [option='2']" and works fine in console and selenium –  bott Jun 11 at 7:20
    
@bott: I did mention that in my answer. I knew I should have added the other option to go with the explanation just in case... –  BoltClock Jun 11 at 7:22
add comment

Using:

"#popup > ul li [option='2']"

works fine in console and selenium!

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.