【问题标题】:Select Any Sibling选择任何兄弟姐妹
【发布时间】:2018-07-24 01:50:07
【问题描述】:

preceding-siblingfollowing-sibling明确选择兄弟姐妹的唯一选项吗?

标记的简化版本

<ui-view>
  <descendant> <!-- 1 -->
    <descendant> <!-- 2 -->
      <descendant> <!-- 3 -->
        <descendant> <!-- 4 -->
          <descendant> <!-- 5 -->
            <sibling>
              <child></child> <!-- comments_author -->
              <child></child> <!-- comments_timestamp -->
            </sibling>
            <sibling></sibling> <!-- comment (in comments_comment) -->

脚本

# 1. Select All Comment Threads
comments_threads = browser.find_elements_by_xpath('//ui-view//div[@class="commentLayout"]')

for thread in comments_threads:
    # 2. Select All Comments in Each Thread
    comments_comment = comments_threads.find_elements_by_xpath('./div[contains(@class, "commentLayout-text")]')

    for comment in comments_comment:
        # 3. Select Author of Each Comment
        # comments_author = comments_threads.find_element_by_xpath('./*[contains(@class, "commentLayout-account")]')

        # 4. Select Timestamp of Each Comment
        # comments_timestamp = comments_threads.find_element_by_xpath('./span[contains(@class, "commentNote")]')

问题是必须针对嵌套循环的每个 comment 项选择 34,我希望我的代码尽可能灵活。

选择任何同级来匹配所需节点将比使用preceding-sibling 匹配所需节点灵活得多。

一种解决方案是选择父节点,然后选择任何匹配特定条件的子节点,但如果可能的话,使用任何兄弟节点作为选择器肯定会更灵活,甚至更有效。

不能选择所有个兄弟姐妹吗?

【问题讨论】:

  • 发布代码从不使用preceding-siblingfollowing-sibling,但询问如何获取所有兄弟姐妹相当令人困惑。如果您发布示例标记并根据标记中的某些不变量解释您尝试选择的内容,您的问题会更清楚。
  • 这听起来像X-Y problem。与其寻求解决问题的帮助,不如编辑您的问题并询问实际问题。你想做什么?
  • 这就是原因,我问你而不是寻求帮助来解决问题,编辑你的问题并询问实际问题。你想做什么?您要自动化手动步骤是什么?
  • @Anthony 这里没有责备游戏。您的问题不清楚,也没有任何代码试验。见:How to create a Minimal, Complete, and Verifiable example.
  • XPath 中没有 preceding-and-following-siblingssiblings 轴,也不需要它们。您拒绝提供实际的minimal reproducible example 而不是草图,这使我们无法为您提供更详细的答案。正如@DebanjanB 所建议的那样,您的问题的结构确实类似于 XY 问题。如果您的问题只是有一个siblings 轴,那么简单的答案是没有。您寻求的“其他选项”将取决于您的实际标记的细节,而不是它的抽象草图,以及您的实际目标,而不是根据感知的最佳方法表达的方法。

标签: python selenium xpath


【解决方案1】:

使用下面的选择器:

//"your div"[position()=1] , just change to any position as you require.

我只是想给出一个想法,但不知道这是否适合你。 请查看此帖子以进一步解释 xpath 中的位置:
http://seleniumone-by-arun.blogspot.com/2013/04/64-position-xpath-function.html

【讨论】:

  • //"your div"[position()=1]可以这样简化//"your div"[1]
【解决方案2】:

我认为这会选择“thisnode”的所有兄弟姐妹:

//thisnode/../*

/.. 表示选择父级(上一级)

/* 表示选择每个子级(返回下一级)

【讨论】:

  • 是的,选择父节点。让我编辑以增加清晰度
【解决方案3】:

XPath 中没有组合的siblings 轴——只有preceding-siblingfollowing-sibling

您通常可以通过元素父级的子级的条件来实现与兄弟元素相关的任何目标。详细信息将特定于目标标记中的不变量。当兄弟姐妹之间的排序很重要时,使用preceding-siblingfollowing-sibling 轴;否则,在父元素的子元素上写条件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-06
    相关资源
    最近更新 更多