3

I'm using Python Selenium to locate element by using nth-child(n).

Below is my html code:

<div id="iopop" style="">
 <div style="" class="">
  <div id="iopoph" class="animated zoomIn" style=" ">
      <span style="" class="gs_hover"></span>
      <b class="in">FALAFEL</b>
      <a iid="128-73" class="itemsub lowend" price="2.99" name="FALAFEL (6)" style="">
          <b class="in">(6)</b>
          <b class="is"></b>
          <b class="ip">2.99</b>
          <b class="iq"></b></a>
      <a iid="128-74" class="itemsub lowend" price="4.99" name="FALAFEL (12)" style="">
          <b class="in">(12)</b>
          <b class="is"></b>
          <b class="ip">4.99</b>
          <b class="iq"></b>
      </a>
      <b class="is"></b>
      <b class="ip"></b>
      <b class="iq"></b>
  </div>
 </div>
</div>

Now I want to locate the first a tag by using nth-child(n) so I tried:

driver.find_element_by_css_selector('div#iopoph a:nth-child(2)').click()

But there is an error says:

NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"div#iopoph a:nth-child(2)"}
(Session info: chrome=79.0.3945.88)

Any friend can help?

DebanjanB
  • 118,661
  • 30
  • 168
  • 217
William
  • 1,666
  • 2
  • 24
  • 50

3 Answers3

1

You were close but you need to consider a couple of things:

  • div#iopoph will identify the parent node, i.e.

    <div id="iopop" style="">
    
  • So you need to traverse to it's grand child node:

    <div id="iopoph" class="animated zoomIn" style=" ">
    
  • To locate it's child elements you can use the following Locator Strategies:

    • Locating <a iid="128-73" class="itemsub lowend" price="2.99" name="FALAFEL (6)" style="">:

      div.animated.zoomIn#iopoph a:nth-of-type(1)
      
    • Locating <a iid="128-74" class="itemsub lowend" price="4.99" name="FALAFEL (12)" style="">:

      div.animated.zoomIn#iopoph a:nth-of-type(2)
      
DebanjanB
  • 118,661
  • 30
  • 168
  • 217
1

you can use this locator a:nth-of-type(2)

1

In your case example-
div#iopop a:nth-child(3) -> returns first a <anchor> tag i.e. <a iid="128-73"

div#iopop a:nth-child(4) -> returns second a <anchor> tag i.e. <a iid="128-74"

nth-child(index):
nth-child(index) method is used to select/get specified index child element. But the specified index element should be same as mentioned before colon ( : ).

In your case-
div#iopoph a:nth-child(2)-> It points to tag and it is not same as the tag you mentioned before : (colon). so it returns NOSUCHELEMENTEXCEPTION

Avinash Pande
  • 1,280
  • 17
  • 17