【问题标题】:How to use the cssSelector :nth-child(n) to locate element in Python Selenium如何使用 cssSelector :nth-child(n) 在 Python Selenium 中定位元素
【发布时间】:2020-04-20 06:06:18
【问题描述】:

我正在使用 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) 来定位第一个 a 标签,所以我尝试了:

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)

有朋友可以帮忙吗?

【问题讨论】:

  • 要定位第一个 &lt;a&gt; 标签,您可以使用 :nth-of-type 代替:'div#iopoph a:nth-of-type(1)'
  • 第一个a是第三个孩子,所以a:nth-child(3)

标签: python selenium selenium-webdriver css-selectors webdriver


【解决方案1】:

在你的例子中-
div#iopop a:nth-child(3) -&gt; returns first a &lt;anchor&gt; tag i.e. &lt;a iid="128-73"

div#iopop a:nth-child(4) -&gt; returns second a &lt;anchor&gt; tag i.e. &lt;a iid="128-74"

nth-child(索引):
nth-child(index) 方法用于选择/获取指定的索引子元素。但指定的索引元素应与冒号(:)之前提到的相同。

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

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

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

        <div id="iopoph" class="animated zoomIn" style=" ">
        
      • 要找到它的子元素,您可以使用以下Locator Strategies

        • 定位&lt;a iid="128-73" class="itemsub lowend" price="2.99" name="FALAFEL (6)" style=""&gt;

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

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

      【讨论】:

        猜你喜欢
        • 2021-12-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-29
        • 2018-12-29
        • 1970-01-01
        相关资源
        最近更新 更多