如何使用cssSelector:nthchild(n)在Python中定位元素

2024-09-20 05:32:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Python Selenium通过使用第n个子元素(n)来定位元素。你知道吗

下面是我的html代码:

<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>

现在我想通过使用第n个child(n)来定位第一个标记,因此我尝试:

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

但有一个错误是:

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)

有朋友能帮忙吗?你知道吗


Tags: in定位ipdividchild元素is
2条回答

你很接近,但你需要考虑以下几点:

  • div#iopoph将标识父节点,即

    <div id="iopop" style="">
    
  • 所以你需要遍历到它的孙子节点:

    <div id="iopoph" class="animated zoomIn" style=" ">
    
  • 要定位其子元素,可以使用以下Locator Strategies

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

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

      div.animated.zoomIn#iopoph a:nth-of-type(2)
      

您可以使用类型(2)的第n个定位器

相关问题 更多 >