Selecting Nth-of-type in selenium

前端 未结 1 1176
北海茫月
北海茫月 2020-12-06 14:26

I\'m trying to use By.cssSelector to grab the nth dom element with class c3 with a structure like this:

相关标签:
1条回答
  • 2020-12-06 14:41

    I'm not enirely sure which one you want to select, but you should play around more with the :nth-* pseudo-classes. Here is a CSS selector that selects all 3 c3's using nth-child()

    div.c1 div.c3:nth-child(1)
    

    Like i said, you haven't really specified which one you want to select.

    but my lack of understanding on nth-of-type is driving me crazy. Can anyone offer insight to why the second 2 don't work or correct my basic lack of comprehension on this selector?

    One thing to keep in mind, is all of the :nth-*() pseudo-classes are dependent on their parents. Let me translate your selector:

    .c1:nth-of-type(2)
    

    Find anything with a class of c1 that is a second child.

    In your case, <body> was most likely the parent, so...

    <body>
      <div .c1 />
      <div .c1 /> // it highlights this one, because it's the 2nd child of the type ".c1"
      <div .c1 />
    </body>
    

    Now let me explain why your other selectors are not working.

    Both .c2:nth-of-type(2) and .c3:nth-of-type(2) are looking at the parent's as well. since you are specifying a parent, it's expecting <body> as the parent. In your case, <body> isn't the parent.. the <div .c1 /> is. In reality, that selector is looking for the DOM -

    <body>
      <div .c1 />
      <div .c2 /> // this **would** be the second nth-of-type, but it's not really this way. 
      <div .c1 />
    </body>
    

    Play around with the different css selectors and pseudo-classes at http://cssdesk.com it's very helpful to actively experiment on your own. you'll figure it out.

    0 讨论(0)
提交回复
热议问题