【问题标题】:How to use css selector nth-of-type and nth-child to locate element in Python Selenium如何使用 css 选择器 nth-of-type 和 nth-child 在 Python Selenium 中定位元素
【发布时间】:2021-12-30 13:51:54
【问题描述】:

下面是如何设置页面的 sn-p。

<class id="class1">
  <ul>
    <li>
      <strong>section 1</strong>
      <a href="link.com/home1">some link 1</a>
    <li>
      <strong>section 2</strong>
      <a href="link.com/home">some link 2</a>
<class id="class1">
  <ul>
    <li>
      <strong>section 3</strong>
      <a href="link.com/home/abc">some link 3</a>
    <li>
      <strong>section 4</strong>
      <a href="link.com/home/def">some link 4</a>

如何在第 2 部分找到 link.com/home?

我认为这会起作用:

.class1:nth-of-type(1) li:nth-child(2) [href*="/home"]

但事实并非如此。它也在第 4 节中找到了链接。我必须使用 *= 因为在不同的环境中 url 前缀会发生变化。

【问题讨论】:

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


    【解决方案1】:

    为了完整起见,我在合适的地方添加了&lt;/li&gt;&lt;/ul&gt;&lt;/class&gt;标签HTML 将是:

    <class id="class1">
      <ul>
        <li>
          <strong>section 1</strong>
          <a href="link.com/home1">some link 1</a>
        </li>
        <li>
          <strong>section 2</strong>
          <a href="link.com/home">some link 2</a>
        </li>
      </ul>
    </class>
    <class id="class1">
      <ul>
        <li>
          <strong>section 3</strong>
          <a href="link.com/home/abc">some link 3</a>
        </li>
        <li>
          <strong>section 4</strong>
          <a href="link.com/home/def">some link 4</a>
        </li>
      </ul>
    </class>
    

    要定位 第 2 节href 属性,您可以使用以下任一Locator Strategies

    • 使用nth-child()

      class#class1 > ul li:nth-child(2) a[href$="home"]
      
    • 使用nth-child()

      class#class1 > ul li:nth-of-type(2) a[href$="home"]
      

    解决方案

    要打印 href 属性的值,您可以使用以下任一Locator Strategies

    • 使用nth-child():

      print(driver.find_element(By.CSS_SELECTOR, "class#class1 > ul li:nth-child(2) a[href$='home']").get_attribute("href"))
      
    • 使用nth-child():

      print(driver.find_element(By.CSS_SELECTOR, "class#class1 > ul li:nth-of-type(2) a[href$='home']").get_attribute("href"))
      

    tl;博士

    What is the difference between p:nth-child(2) and p:nth-of-type(2)?

    【讨论】:

    • 嗨,谢谢,这有效。我能再问你一个问题吗?如果两个 URL 完全相同,但我只想要第 2 节中的那个,怎么办?这可能吗?
    • 您能就您的新要求提出一个新问题吗?
    猜你喜欢
    • 2013-05-09
    • 1970-01-01
    • 1970-01-01
    • 2012-03-07
    • 2013-11-23
    • 2015-12-20
    • 2016-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多