0

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?

    2 Answers 2

    3

    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']"); 
    2
    • 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
      CommentedJun 11, 2014 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
      CommentedJun 11, 2014 at 7:22
    0

    Using:

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

    works fine in console and selenium!

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.