如何使用 cssSelector :nth-child(n) 在 Python Selenium 中定位元素



我正在使用Python Selenium通过使用nth-child(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>

现在我想使用 nth-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)

有朋友可以帮忙吗?

你很接近,但你需要考虑几件事:

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

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

    <div id="iopoph" class="animated zoomIn" style=" ">
    
  • 要查找其子元素,您可以使用以下定位器策略:

    • 定位<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)
      

您可以使用此定位器 a:nth-of-type(2(

在你的例子中 -
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(方法用于选择/获取指定的索引子元素。 但是指定的索引元素应该与冒号 ( : ( 之前提到的相同。

在您的情况下 -
div#iopoph a:nth-child(2)-> 它指向标签,它与您之前提到的标签不同:(冒号(。 所以它返回 NOSUCHELEMENTEXCEPTION

最新更新